https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
需要元音字母保存起來,然后看是否字符串中的字符有這些元音字母。
也是用到了雙指針,因為需要交換,所以要定一個從左遍歷,一個從右遍歷,
如果不是元音的話,就直接放在新的字符串中,如果是元音的話,就和另外一個指針也是元音的交換順序。
class solution{
? ? private final static HashSet<Character> vowels = new HashSet<>(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
? ? public String reverseVowels(String s){
? ? ? ? if(s == null) return null;
? ? ? ? int i = 0;
? ? ? ? int j = s.length() - 1;
? ? ? ? char[] result = new char[s.length()];
? ? ? ? while( i <= j){
? ? ? ? ? ? char ci = s.charAt(i);
? ? ? ? ? ? char cj = s.charAt(j);
? ? ? ? ? ? if(!vowels.contains(ci)){
? ? ? ? ? ? ? ? result[i++] = ci;
? ? ? ? ? ? }
? ? ? ? ? ? else if(!vowels.contains(cj)){
? ? ? ? ? ? ? ? result[j++] = cj;
? ? ? ? ? ? }
? ? ? ? ? ? else{
? ? ? ? ? ? result[i++] = cj;
? ? ? ? ? ? result[j++] = ci;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return new String(result);
? ? }
}
定義了一個HashSet,之后要調(diào)用它的contains方法,判斷遍歷到的字符是否是元音
在new這個HashSet的時候用了Arrays.asList方法,并且還是用char的包裝類Character
過程中還使用了String的charAt方法,返回的是指定索引處的字符
? ??????????
?????????????