LeetCode C++ 345. Reverse Vowels of a String【String】简单

    科技2025-09-12  78

    Write a function that takes a string as input and reverse only the vowels of a string.

    Example 1:

    Input: "hello" Output: "holle"

    Example 2:

    Input: "leetcode" Output: "leotcede"

    Note: The vowels does not include the letter "y" .

    题意:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。


    解法

    很简单的双指针题目,只是需要注意范围检查和大小写的问题。代码如下:

    class Solution { private: bool isvowel(char c) { c = tolower(c); return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } public: string reverseVowels(string s) { if (s.size() <= 1) return s; int left = 0, right = s.size() - 1; while (left < right) { while (left < right && !isvowel(s[left])) ++left; while (left < right && !isvowel(s[right])) --right; if (left < right) swap(s[left++], s[right--]); else break; } return s; } };

    效率如下:

    执行用时:4 ms, 在所有 C++ 提交中击败了99.62% 的用户 内存消耗:7.7 MB, 在所有 C++ 提交中击败了60.21% 的用户
    Processed: 0.012, SQL: 8