首页 > 代码库 > LeetCode 345 Reverse Vowels of a String

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