Saturday, October 21, 2017

345. 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".
Note:
The vowels does not include the letter "y".

Solution:
Convert the string to a char array, then use one pointer to find vowels from left to right, and use another pointer to find vowels from right to left. Swap vowels when we process the char array.
Time complexity: O(n)

 public String reverseVowels(String s) {  
     char[] sarr=s.toCharArray();  
     int i=0;  
     int j=sarr.length-1;  
     while(i<j){  
       while(i<j && !isVowel(sarr[i])) i++;  
       while(i<j && !isVowel(sarr[j])) j--;  
       char c=sarr[i];  
       sarr[i++]=sarr[j];  
       sarr[j--]=c;  
     }  
     return new String(sarr);  
   }  
   public boolean isVowel(char c){  
     return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'  
       || c=='A'||c=='E'||c=='I'||c=='O'||c=='U';  
   }  

No comments:

Post a Comment