LeetCode:Reverse Vowels of a String

Reverse Vowels of a String

   


Total Accepted: 8150  Total Submissions: 23213  Difficulty: Easy

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".

Subscribe to see which companies asked this question

Hide Tags
  Two Pointers String
Hide Similar Problems
  (E) Reverse String



















code:

public class Solution {
    
    public boolean isVowel(char c) {
        if('A' <= c && c <= 'Z') c += 'a'-'A';
        return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
    }
    
    public String reverseVowels(String s) {
        int len = s.length();
        char[] chs = s.toCharArray();
        int i=0,j=len-1;
        while(i<j) {
            while(i<j && !isVowel(chs[i])) i++;
            while(i<j && !isVowel(chs[j])) j--;
            char t = chs[i];
            chs[i] = chs[j];
            chs[j] = t;
            i++;
            j--;
        }
        return new String(chs);
    }
}



你可能感兴趣的:(LeetCode,reverse,of,a,Vowels)