Reverse Vowels of a String (E)
題目
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
題意
只將字串中的元音字母逆置,
思路
Two Pointers,只將元音字母兩兩交換,
代碼實作
Java
class Solution {
public String reverseVowels(String s) {
char[] array = s.toCharArray();
Set<Character> set = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !set.contains(array[left])) {
left++;
}
while (left < right && !set.contains(array[right])) {
right--;
}
if (left < right) {
char tmp = array[left];
array[left++] = array[right];
array[right--] = tmp;
}
}
return new String(array);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/36573.html
標籤:其他
