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

LeetCode Reverse Vowels of a String

原题链接在这里: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".

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

题解:

典型的two pointers, 到了vowel时对调.

Time Complexity: O(s.length()). Space:O(s.length()), 因为建立了char array.

AC Java:

 1 public class Solution { 2     public String reverseVowels(String s) { 3         HashSet<Character> hs = new HashSet<Character>(); 4         hs.add(‘A‘); 5         hs.add(‘a‘); 6         hs.add(‘E‘); 7         hs.add(‘e‘); 8         hs.add(‘I‘); 9         hs.add(‘i‘);10         hs.add(‘O‘);11         hs.add(‘o‘);12         hs.add(‘U‘);13         hs.add(‘u‘);14         15         char [] charArr = s.toCharArray();16         int i = 0;17         int j = charArr.length-1;18         while(i<j){19             while(i<j && !hs.contains(charArr[i])){20                 i++;21             }22             while(i<j && !hs.contains(charArr[j])){23                 j--;24             }25             if(i<j){26                 swap(charArr, i, j);27                 i++;28                 j--;29             }30         }31         32         return new String(charArr);33      }34      35      private void swap(char [] arr, int i, int j){36          char temp = arr[i];37          arr[i] = arr[j];38          arr[j] = temp;39      }40 }

 

LeetCode Reverse Vowels of a String