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

LeetCode 345 Reverse Vowels of a String

时间:2016-09-03 16:25:41      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

思路:

左右双指针,遇到元音后停止,二者交换,之后继续各自前进,直至双指针相遇为止。

 

解法:

 1 import java.util.Set;
 2 
 3 public class Solution
 4 {
 5     public String reverseVowels(String s)
 6     {
 7         Set<Character> set = new HashSet<>();
 8         char[] vowelArray = {‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘, ‘A‘, ‘E‘, ‘I‘, ‘O‘, ‘U‘};
 9         char[] sArray = s.toCharArray();
10 
11         for(int i = 0; i < vowelArray.length; i++)
12             set.add(vowelArray[i]);
13 
14         int left = 0;
15         int right = sArray.length - 1;
16 
17         while(left < right)
18         {
19             while((!set.contains(sArray[left])) && (left < right))
20                 left++;
21             while((!set.contains(sArray[right])) && (left < right))
22                 right++;
23 
24             if(set.contains(sArray[left]) && set.contains(sArray[right]))
25             {
26                 char temp = sArray[left];
27                 sArray[left] = sArray[right];
28                 sArray[right] = temp;
29                 left++;
30                 right--;
31             }
32         }
33 
34         return String.valueOf(sArray);
35     }
36 }

 

LeetCode 345 Reverse Vowels of a String

标签:

原文地址:http://www.cnblogs.com/wood-python/p/5837139.html

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