Monday, July 25, 2016

LeetCode [345] Reverse Vowels of a String

 345. Reverse Vowels of a String

Easy

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    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';
    }
    public String reverseVowels(String s) {
        StringBuilder sb = new StringBuilder(s);
        int l = 0, r = s.length()-1;
        while(l<r){
            if(!isVowel(sb.charAt(l))) l++;
            else if(!isVowel(sb.charAt(r))) r--;
            else{
                char t = sb.charAt(l);
                sb.setCharAt(l, sb.charAt(r));
                sb.setCharAt(r, t);
                l++;
                r--;
            }
        }
        return sb.toString();
    }
}

No comments:

Post a Comment