【Leetcode】Reverse Vowels of a String

1577 ワード

タイトルリンク:https://leetcode.com/problems/reverse-vowels-of-a-string/
タイトル:
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1: Given s = "hello", return "holle".
Example 2: Given s = "leetcode", return "leotcede".
考え方:
easy
アルゴリズム:
public String reverseVowels(String s) {  
       char c[] = s.toCharArray();  
       Set<String> vowels = new HashSet<String>();  
       vowels.add("a");  
       vowels.add("e");  
       vowels.add("i");  
       vowels.add("o");  
       vowels.add("u");  
       vowels.add("A");  
       vowels.add("E");  
       vowels.add("I");  
       vowels.add("O");  
       vowels.add("U");  
       int v1=-1,v2=-1;  
       for(int start=0,end=c.length-1;start<end;){  
        if(v1==-1){  
            if(vowels.contains(c[start]+""))  
                v1 = start;  
            else  
                start++;  
        }  
        if(v2==-1){  
            if(vowels.contains(c[end]+""))  
                v2 = end;  
            else  
                end--;  
        }  
          
        if(v1!=-1&&v2!=-1){  
            char tmp = c[v1];  
            c[v1] = c[v2];  
            c[v2] = tmp;  
            v1 = -1;  
            v2 = -1;  
            start++;  
            end--;  
        }  
              
       }  
         
       return new String(c);  
   }