344. Reverse String

Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh".

S: two-pointer

用两个指针从字符串两段向中间扫描。同时把这两个指针对应的字符对换 。

string reverseString(string s) {
    for (int l = 0, r = s.size()-1; l < r; ++l, --r) swap(s[l], s[r]);
    return s;
}

345. Reverse Vows of a String

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

S: two pointer

    unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    string reverseVowels(string s) {
        for(int l = 0, r = s.size()-1; l < r; ++l){
            if(isVowel(s[l])){
                while((!isVowel(s[r])) && l<r) r--;
                swap(s[l], s[r--]);
            }
        }
        return s;
    }
    bool isVowel(char letter){
        if(vowels.find(letter) != vowels.end()) return true;
        return false;
    }

results matching ""

    No results matching ""