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方法模叙,返回的是指定索引處的字符
? ??????????
?????????????