344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question
public class Solution { public String reverseString(String s) { if(s==null) return ""; char c[] = s.toCharArray(); int len = s.length(); int i=0; int j=len-1; while(i<j){ char tmp = c[i]; c[i] = c[j]; c[j] = tmp; ++i; --j; } return new String(c); } }
345. Reverse Vowels of a String
Total Accepted: 4116 Total Submissions: 11368 Difficulty: Easy
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Subscribe to see which companies asked this question
采用快排的partition函数来对字符串进行翻转
public class Solution { public String reverseVowels(String s) { if(s==null){ return ""; } char[] c = s.toCharArray(); int left = 0; int right = c.length-1; while(left<right){ while(left<right&&!isVowel(c[left])){ ++left; } while(left<right&&!isVowel(c[right])){ --right; } char tmp = c[left]; c[left] = c[right]; c[right] = tmp; ++left; --right; } return new String(c); } //检查一个字符是否是元音字符 public boolean isVowel(char c){ if(c==‘a‘||c==‘e‘||c==‘i‘||c==‘o‘||c==‘u‘||c==‘A‘||c==‘E‘||c==‘I‘||c==‘O‘||c==‘U‘) return true; else return false; } }
时间: 2024-11-06 16:42:54