1. 程式人生 > >345 reverse vowels of a string

345 reverse vowels of a string

關鍵:找一個容器儲存可換位置的字母

1. 自己

使用陣列儲存

class Solution {     public String reverseVowels(String s) {         int[] map= new int[256];         map['a']= map['A']= 1;         map['e']= map['E']= 1;         map['i']= map['I']= 1;         map['o']= map['O']= 1;         map['u']= map['U']= 1;                  char[] tmp= s.toCharArray();         int st= 0, e= tmp.length-1;         while(st< e){             if(map[tmp[st]]==1 && map[tmp[e]]==1){                 char ch= tmp[st];                 tmp[st]= tmp[e];                 tmp[e]= ch;                 st++;e--;             }if(map[tmp[st]]==0){                 st++;             }if(map[tmp[e]]==0){                  e--;             }                     }         return new String(tmp);     } }

2. 參考

用set存貯

public class Solution {     public String reverseVowels(String s) {         char[] list=s.toCharArray();         Set<Character> set=new HashSet<>();         set.add('a');         set.add('e');         set.add('i');         set.add('o');         set.add('u');         set.add('A');         set.add('E');         set.add('I');         set.add('O');         set.add('U');         for (int i=0, j=list.length-1; i<j; ) {             if (!set.contains(list[i])) {                 i++;                 continue;             }             if (!set.contains(list[j])) {                 j--;                 continue;             }             char temp=list[i];             list[i]=list[j];             list[j]=temp;             i++;             j--;         }         return String.valueOf(list);     } }

或用另一種方式建立含值的set:

Set<Character> vowels = new HashSet<>(Arrays.asList(new Character[]{'a','e','i','o','u','A','E','I','O','U'}));

3. 參考

使用string儲存,contains判斷

public class Solution { public String reverseVowels(String s) {     if(s == null || s.length()==0) return s;     String vowels = "aeiouAEIOU";     char[] chars = s.toCharArray();     int start = 0;     int end = s.length()-1;     while(start<end){                  while(start<end && !vowels.contains(chars[start]+"")){             start++;         }                  while(start<end && !vowels.contains(chars[end]+"")){             end--;         }                  char temp = chars[start];         chars[start] = chars[end];         chars[end] = temp;                  start++;         end--;     }     return new String(chars); }