LeetCode 345 Reverse Vowels of a String

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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:
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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode #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

[LeetCode]345 Reverse Vowels of a String

leetcode 345. Reverse Vowels of a String