序
本文主要記錄一下leetcode之反轉(zhuǎn)字符串中的元音字母
題目
編寫一個函數(shù),以字符串作為輸入,反轉(zhuǎn)該字符串中的元音字母。
示例 1:
輸入:"hello"
輸出:"holle"
示例 2:
輸入:"leetcode"
輸出:"leotcede"
提示:
元音字母不包含字母 "y" 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
題解
class Solution {
Set<Character> set = new HashSet(){{
add('a');
add('e');
add('i');
add('o');
add('u');
add('A');
add('E');
add('I');
add('O');
add('U');
}};
public String reverseVowels(String s) {
int i = 0;
int j = s.length() - 1;
char[] chars = s.toCharArray();
while(i < j) {
while (!set.contains(chars[i]) && i<j) {
i++;
}
while (!set.contains(chars[j]) && i<j) {
j--;
}
if (i < j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
i++;
j--;
}
}
return new String(chars);
}
}
小結(jié)
這里先使用HashSet存放大小寫的元音字母,之后使用頭尾指針同時對字符串數(shù)組進行遍歷,當i指向的字符與j指向的字符都是元音時,進行交換同時更新指針,不是元音字符時僅僅更新指針。