Description
https://leetcode.com/problems/reverse-vowels-of-a-string/
给定一个字符串,反转其中的元音字符序列。
Input: "leetcode"
Output: "leotcede"
Solving Ideas
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Solution
class Solution {
public String reverseVowels(String s) {
Set<Character> vowels = new HashSet<>();
for (char ch : "aeiouAEIOU".toCharArray()) vowels.add(ch);
char[] str = s.toCharArray();
int left = 0, right = str.length - 1;
while (left < right) {
while (left < right && !vowels.contains(str[left])) left++;
while (left < right && !vowels.contains(str[right])) right--;
char tmp = str[left];
str[left++] = str[right];
str[right--] = tmp;
}
return new String(str);
}
}