Skip to content

Commit 92b54ff

Browse files
refactor 345
1 parent a92e9d1 commit 92b54ff

File tree

1 file changed

+27
-37
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-37
lines changed
Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.Arrays;
34
import java.util.HashSet;
45
import java.util.Set;
56

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.
711
812
Example 1:
913
Given s = "hello", return "holle".
@@ -14,45 +18,31 @@
1418
Note:
1519
The vowels does not include the letter "y".*/
1620
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);
3742
i++;
38-
left = s.charAt(i);
39-
}
40-
while (i < j && !vowels.contains(right)) {
4143
j--;
42-
right = s.charAt(j);
4344
}
44-
char temp = left;
45-
sb.setCharAt(i, right);
46-
sb.setCharAt(j, temp);
47-
i++;
48-
j--;
45+
return sb.toString();
4946
}
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));
5747
}
5848
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy