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

【Leetcode】Reverse Vowels of a String

时间:2016-05-30 15:31:58      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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".

思路:

easy

算法

public String reverseVowels(String s) {  
       char c[] = s.toCharArray();  
       Set<String> vowels = new HashSet<String>();  
       vowels.add("a");  
       vowels.add("e");  
       vowels.add("i");  
       vowels.add("o");  
       vowels.add("u");  
       vowels.add("A");  
       vowels.add("E");  
       vowels.add("I");  
       vowels.add("O");  
       vowels.add("U");  
       int v1=-1,v2=-1;  
       for(int start=0,end=c.length-1;start<end;){  
        if(v1==-1){  
            if(vowels.contains(c[start]+""))  
                v1 = start;  
            else  
                start++;  
        }  
        if(v2==-1){  
            if(vowels.contains(c[end]+""))  
                v2 = end;  
            else  
                end--;  
        }  
          
        if(v1!=-1&&v2!=-1){  
            char tmp = c[v1];  
            c[v1] = c[v2];  
            c[v2] = tmp;  
            v1 = -1;  
            v2 = -1;  
            start++;  
            end--;  
        }  
              
       }  
         
       return new String(c);  
   }  


【Leetcode】Reverse Vowels of a String

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51520478

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