【LeetCode】345. Reverse Vowels of a String
Difficulty: Easy
More:【目录】LeetCode Java实现
Description
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:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Intuition
Using two pointers.
Solution
private final static HashSet<Character> vowels = new HashSet<Character> ( Arrays.asList('a','e','i','o','u','A','E','I','O','U')); public String reverseVowels(String s) { if(s==null || s.length()<=0) return s; int i=0, j=s.length()-1; char[] chars = new char[s.length()]; while(i<=j){ char ci=s.charAt(i); char cj=s.charAt(j); if(!vowels.contains(ci)) chars[i++]=ci; else if(!vowels.contains(cj)) chars[j--]=cj; else{ chars[i++]=cj; chars[j--]=ci; } } return String.valueOf(chars); }
Complexity
Time complexity : O(n)
Space complexity : O(1)
What I've learned
1.The use of two pointers.
More:【目录】LeetCode Java实现