Thursday, June 2, 2016

Leetcode: 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".
Solution:
Just use two point from start and end of the string, respectively. 
BE CAREFUL ABOUT THE UPPER CASE!

Code(Java):
public class Solution {
    public String reverseVowels(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        
        char[] cs = s.toCharArray();
        
        int start = 0;
        int end = cs.length - 1;
        
        while (start < end) {
            while (start < end && !isVowel(cs[start])) {
                start++;
            }
            
            while (start < end && !isVowel(cs[end])) {
                end--;
            }
            
            if (start < end) {
                swap(cs, start, end);
                start++;
                end--;
            }
        }
        
        return new String(cs);
    }
    
    private boolean isVowel(char b) {
        char c = Character.toLowerCase(b);
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
    
    private void swap(char[] cs, int start, int end) {
        char temp = cs[start];
        cs[start] = cs[end];
        cs[end] = temp;
    }
}


No comments:

Post a Comment