345. Reverse Vowels of a String

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

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

class Solution {
    public String reverseVowels(String s) {
        char[] c = s.toCharArray();
        List<Character> list = new ArrayList();
        list.add(‘a‘);
        list.add(‘e‘);
        list.add(‘i‘);
        list.add(‘o‘);
        list.add(‘u‘);
        list.add(‘A‘);
        list.add(‘E‘);
        list.add(‘I‘);
        list.add(‘O‘);
        list.add(‘U‘);
        String res = "";
        if(s.length() == 0) return res;
        int st = 0, end = s.length() - 1;
        while(st < end){
            char t1 = c[st];
            char t2 = c[end];
            if(list.contains(t1) && list.contains(t2)){
                char tmp = c[st];
                c[st] = c[end];
                c[end] = tmp;
                st++;
                end--;
            }
            else if(list.contains(t1) && !list.contains(t2)) end--;
            else if(!list.contains(t1) && list.contains(t2)) st++;
            else{
                end--;
                st++;
            }
        }
        return(String.valueOf(c));
    }
}

 

class Solution {
    public String reverseVowels(String s) {
        char[] c = s.toCharArray();
        String ind = "aeiouAEIOU";
        String res = "";
        if(s.length() == 0) return res;
        int st = 0, end = s.length() - 1;
        while(st < end){
            char t1 = c[st];
            char t2 = c[end];
            if(ind.indexOf(t1)!=-1 && ind.indexOf(t2)!=-1){
                char tmp = c[st];
                c[st] = c[end];
                c[end] = tmp;
                st++;
                end--;
            }
            else if(ind.indexOf(t1)!=-1 && ind.indexOf(t2) == -1) end--;
            else if(ind.indexOf(t1) == -1 && ind.indexOf(t2)!=-1) st++;
            else{
                end--;
                st++;
            }
        }
        return(String.valueOf(c));
    }
}

 

以上是关于345. Reverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 345. Reverse Vowels of a String

LeetCode #345 Reverse Vowels of a String

[LeetCode]345 Reverse Vowels of a String

345. Reverse Vowels of a Stringeasy

LeetCode 345. Reverse Vowels of a String

345. Reverse Vowels of a String