-
Notifications
You must be signed in to change notification settings - Fork 22
/
345. Reverse Vowels of a String.java
executable file
·96 lines (82 loc) · 2.53 KB
/
345. Reverse Vowels of a String.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
E
tags: Two Pointers, String
vowels: 元音字母. 要求reverse所有元音字母.
##### 方法1: two pointer.
- 前后两个指针, 在while loop里面跑.
- 注意 i<j, 一旦相遇, 就break.
- 找到合适的, 就做swap.
- StringBuffer可以 sb.setCharAt()记得用.
- O(n)
##### 方法2:
拿出所有vowels, 反过来放进去. O(n)
```
/**
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
*/
/*
Thoughts:
vowels: a e i o u A E I O U
Use i,j to find front and end vowels, and swap them.
*/
class Solution {
public String reverseVowels(String s) {
if (s == null || s.length() == 0) {
return s;
}
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
StringBuffer sb = new StringBuffer(s);
int maxIndex = sb.length() - 1;
int i = 0;
int j = maxIndex;
while (i < j) {
while (i < maxIndex && !vowels.contains(sb.charAt(i))) i++;
while (j > 0 && !vowels.contains(sb.charAt(j))) j--;
if (i < j && vowels.contains(sb.charAt(i)) && vowels.contains(sb.charAt(j))) {
char letter = sb.charAt(j);
sb.setCharAt(j, sb.charAt(i));
sb.setCharAt(i, letter);
j--;
i++;
}
}
return sb.toString();
}
}
/*
Thoughts:
vowels: a e i o u A E I O U
HashMap, store the <pos, letter> and put them back in reverse order.
*/
class Solution {
public String reverseVowels(String s) {
if (s == null || s.length() == 0) {
return s;
}
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
List<Character> matches = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (vowels.contains(s.charAt(i))) {
matches.add(s.charAt(i));
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if (vowels.contains(letter)) {
int lastMatchIndex = matches.size() - 1;
sb.append(matches.get(lastMatchIndex));
matches.remove(lastMatchIndex);
} else {
sb.append(letter);
}
}
return sb.toString();
}
}
```