2017年12月13日 星期三

[LeetCode] 345. Reverse Vowels of a String

轉自LeetCode

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".
<Solution>

思考如下
  • 用一個 HashSet 來查目前的字母是不是母音
  • 用兩個指標,分別從兩端開始找母音,找到就交換
code 如下

Java
class Solution {
public String reverseVowels(String s) {
final HashSet<Character> vowels = new HashSet<>();
int front = 0, end = s.length()-1;
char[] ans = s.toCharArray();
char tmp;
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
vowels.add('A');
vowels.add('E');
vowels.add('I');
vowels.add('O');
vowels.add('U');
while(front < end) {
while(front < end && !vowels.contains(ans[front])) {
++front;
}
while(front < end && !vowels.contains(ans[end])) {
--end;
}
if(front < end) {
tmp = ans[front];
ans[front++] = ans[end];
ans[end--] = tmp;
}
}
return new String(ans);
}
}
C++
class Solution {
public:
string reverseVowels(string s) {
unordered_set<char> table;
table.insert('a');
table.insert('e');
table.insert('i');
table.insert('o');
table.insert('u');
table.insert('A');
table.insert('E');
table.insert('I');
table.insert('O');
table.insert('U');
int left = 0, right = s.length()-1;
while(left < right) {
while(left < right && table.find(s[left]) == table.end()) {
++left;
}
while(left < right && table.find(s[right]) == table.end()) {
--right;
}
if(left < right) {
swap(s[left++], s[right--]);
}
}
return s;
}
};

沒有留言:

張貼留言