玩命加载中 . . .

344/345-反转字符串


LeetCode 344. Reverse String

LeetCode-344

Write a function that reverses a string. The input string is given as an array of characters s.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

method: 反向双指针

两个指针从两边同时向中间遍历,不断交换元素
void reverseString(vector<char>& s) {
    int l = 0, r = s.size() - 1;
    while (l < r) {
        swap(s[l], s[r]);
        l++;
        r--;
    }
}

LeetCode 345. Reverse Vowels of a String

LeetCode-345

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"

method: 集合存储元音字母

string reverseVowels(string s) {
    set<char> st{'a','e','i','o','u','A','E','I','O','U'};
    int l = 0, r = s.size() - 1;
    while (l < r) {
        while (l < r && st.find(s[l]) == st.end()) l++;
        while (l < r && st.find(s[r]) == st.end()) r--;
        swap(s[l], s[r]);
        l++;
        r--;
    }
    return s;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录