345. Reverse Vowels of a String
題目:
Given a string?s, reverse only all the vowels in the string and return it.
The vowels are?'a',?'e',?'i',?'o', and?'u', and they can appear in both cases.
Example 1:
Input: s = "hello" Output: "holle"Example 2:
Input: s = "leetcode" Output: "leotcede"Constraints:
- 1 <= s.length <= 3 * 105
- s?consist of?printable ASCII?characters.
思路:
要交換位置,明顯的雙指針。先用哈希set記錄下元音,可以只記錄全大寫或者全小寫,在判斷的時候多寫一些語句也行,不過這里偷懶就把大小寫元音都記錄下來了。兩個指針分別index = 0 和 n - 1,只要左指針的當前字母不在哈希set內,右移;同理右指針的當前字母不在哈希set內就左移,如果當前左指針index小于右指針index,則交換元素并且再次移動指針。最后返回字符串即可。
代碼:
class Solution {
public:
? ? string reverseVowels(string s) {
? ? ? ? unordered_set<char> mp= {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
? ? ? ? int n = s.size(), i = 0, j = n - 1;
? ? ? ? while (i < j) {
? ? ? ? ? ? while (i < n && !mp.count(s[i]))
? ? ? ? ? ? ? ? i++;
? ? ? ? ? ? while ( j > 0 && !mp.count(s[j]))
? ? ? ? ? ? ? ? j--;
? ? ? ? ? ? if (i < j) {
? ? ? ? ? ? ? ? swap(s[i], s[j]);
? ? ? ? ? ? ? ? i++;
? ? ? ? ? ? ? ? j--;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return s;
? ? }
};
總結
以上是生活随笔為你收集整理的345. Reverse Vowels of a String的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最好用AI抠图的软件,方便你,我,他。
- 下一篇: B. All the Vowels Pl