码迷,mamicode.com
首页 > 其他好文 > 详细

345. Reverse Vowels of a String

时间:2019-11-09 11:53:44      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:class   list   string   amp   cti   val   UNC   length   include   

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

标签:class   list   string   amp   cti   val   UNC   length   include   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11824431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!