1482. Minimum Number of Days to Make m Bouquets

Given a string s, reverse only all the vowels in the string and return it.

The vowels are ‘a’, ’e’, ‘i’, ‘o’, and ‘u’, and they can appear in both cases.

1
2
3
4
5
6
7
8
9
Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
    public String reverseVowels(String s) {
        Set<Character> vowels = new HashSet<>();
        vowels.addAll(Arrays.asList('a', 'e', 'i', 'o', 'u', 
                                    'A', 'E', 'I', 'O', 'U'));
        
        int lo = 0;
        int hi = s.length() - 1;
        
        char[] word = s.toCharArray();
        
        while (lo < hi) {
            
            while (lo < hi && !vowels.contains(word[lo])) {
                lo++;
            }
            
            while (lo < hi && !vowels.contains(word[hi])) {
                hi--;
            } 
            
            char c = word[lo];
            word[lo] = word[hi];
            word[hi] = c;
            
            lo++;
            hi--;
        }
        
        
        return new String(word);
    }
}