LeetCode No345. Reverse Vowels of a String

1. 題目描述

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

2. 思路

  1. 找出所有的元音字母,保存下來,並將其替換成’*’
  2. 利用保存下來的元音字符串,對原字符串中的’*’進行逆序替換

3. 算法

class Solution {
public:
    string reverseVowels(string s) {
        string vowels;

        auto pos = s.find_first_of("aAeEiIoOuU");
        while (pos != string::npos) {
            vowels += s[pos];
            s[pos] = '*';
            pos = s.find_first_of("aAeEiIoOuU", pos + 1);
        }
        for (int i = vowels.size() - 1, j = 0; i >= 0 && j < s.size(); --i) {
            while (s[j] != '*')  ++j;
            s[j] = vowels[i];
        }
        return s;
    }
};

4. 參考資料

  1. http://www.cplusplus.com/reference/string/string/
發佈了69 篇原創文章 · 獲贊 15 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章