寫在前面
- 難度:簡單
for
循環 + 翻轉待逆序數組 + 字符串更新拼接
題目詳情
編寫一個函數,以字符串作爲輸入,反轉該字符串中的元音字母。
示例 1:
輸入: "hello"
輸出: "holle"
示例 2:
輸入: "leetcode"
輸出: "leotcede"
說明:
元音字母不包含字母"y"。
ac代碼
class Solution
{
public:
string reverseVowels(string s)
{
vector<int> nums;
vector<char> chs;
for(int i=0; i<s.size(); i++)
{
char lch = tolower(s[i]);
if(lch == 'a' || lch == 'e' || lch == 'i' || lch == 'o' || lch == 'u')
{
nums.push_back(i);
chs.push_back(s[i]);
}
}
reverse(chs.begin(), chs.end());
for(int i=0; i<nums.size(); i++)
s[nums[i]] = chs[i];
return s;
}
};