|
4 | 4 | import java.util.HashSet;
|
5 | 5 | import java.util.Set;
|
6 | 6 |
|
7 |
| -/** |
8 |
| - * 345. Reverse Vowels of a String |
9 |
| - * |
10 |
| - * Write a function that takes a string as input and reverse only the vowels of a string. |
11 |
| -
|
12 |
| - Example 1: |
13 |
| - Given s = "hello", return "holle". |
14 |
| -
|
15 |
| - Example 2: |
16 |
| - Given s = "leetcode", return "leotcede". |
17 |
| -
|
18 |
| - Note: |
19 |
| - The vowels does not include the letter "y".*/ |
20 | 7 | public class _345 {
|
21 |
| - public static class Solution1 { |
22 |
| - public String reverseVowels(String s) { |
23 |
| - StringBuilder sb = new StringBuilder(s); |
24 |
| - Set<Character> vowels = new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); |
25 |
| - //use two pointers approach would be the fastest |
26 |
| - int i = 0; |
27 |
| - int j = s.length() - 1; |
28 |
| - while (i < j) { |
29 |
| - char left = s.charAt(i); |
30 |
| - char right = s.charAt(j); |
31 |
| - while (i < j && !vowels.contains(left)) { |
32 |
| - i++; |
33 |
| - left = s.charAt(i); |
34 |
| - } |
35 |
| - while (i < j && !vowels.contains(right)) { |
36 |
| - j--; |
37 |
| - right = s.charAt(j); |
38 |
| - } |
39 |
| - char temp = left; |
40 |
| - sb.setCharAt(i, right); |
41 |
| - sb.setCharAt(j, temp); |
42 |
| - i++; |
43 |
| - j--; |
44 |
| - } |
45 |
| - return sb.toString(); |
46 |
| - } |
47 |
| - } |
| 8 | + public static class Solution1 { |
| 9 | + public String reverseVowels(String s) { |
| 10 | + StringBuilder sb = new StringBuilder(s); |
| 11 | + Set<Character> vowels = new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); |
| 12 | + //use two pointers approach would be the fastest |
| 13 | + int i = 0; |
| 14 | + int j = s.length() - 1; |
| 15 | + while (i < j) { |
| 16 | + char left = s.charAt(i); |
| 17 | + char right = s.charAt(j); |
| 18 | + while (i < j && !vowels.contains(left)) { |
| 19 | + i++; |
| 20 | + left = s.charAt(i); |
| 21 | + } |
| 22 | + while (i < j && !vowels.contains(right)) { |
| 23 | + j--; |
| 24 | + right = s.charAt(j); |
| 25 | + } |
| 26 | + char temp = left; |
| 27 | + sb.setCharAt(i, right); |
| 28 | + sb.setCharAt(j, temp); |
| 29 | + i++; |
| 30 | + j--; |
| 31 | + } |
| 32 | + return sb.toString(); |
| 33 | + } |
| 34 | + } |
48 | 35 | }
|
0 commit comments