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".
Note:
The vowels does not include the letter "y".
这道题一开始没想到stirng可以变成char的array,就做复杂了。。。边界的时候还需要挺注意的。
public class Solution { public String reverseVowels(String s) { if (s == null || s.length() == 0) { return s; } int left = 0, right = s.length() - 1; Set<Character> vowel = new HashSet<>(Arrays.asList(new Character[] {‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘, ‘A‘, ‘E‘, ‘I‘, ‘O‘, ‘U‘})); StringBuilder newS = new StringBuilder(); while (left < s.length()) { while (left < s.length() && !vowel.contains(s.charAt(left))) { newS.append(s.charAt(left)); left++; } while (right >= 0 && !vowel.contains(s.charAt(right))) { right--; } if (right >= 0) { newS.append(s.charAt(right)); } left++; right--; } return newS.toString(); } }
如果变成char array就很好做了
public class Solution { public String reverseVowels(String s) { if (s == null || s.length() == 0) { return s; } int left = 0, right = s.length() - 1; Set<Character> vowel = new HashSet<>(Arrays.asList(new Character[] {‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘, ‘A‘, ‘E‘, ‘I‘, ‘O‘, ‘U‘})); char[] str = s.toCharArray(); while (left < right) { while (left < right && !vowel.contains(str[left])) { left++; } while (left < right && !vowel.contains(str[right])) { right--; } char tmp = str[left]; str[left] = str[right]; str[right] = tmp; left++; right--; } return new String(str); } }
需要注意的是char数组转成string有这两种方法:
new String(charArray);
String.valueOf(charArray);
时间: 2024-10-09 22:59:27