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