leetcode 355 翻转字符串中的元音

    xiaoxiao2022-07-07  193

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

    示例 1:

    输入: “hello” 输出: “holle” 示例 2:

    输入: “leetcode” 输出: “leotcede”

    C++ 版本:

    class Solution { public: string reverseVowels(string s) { int i = nextVowelIndex(s, 0); int j = preVowelIndex(s, s.size() - 1); while(i < j){ swap(s[i], s[j]); i = nextVowelIndex(s, i + 1); j = preVowelIndex(s, j - 1); } return s; } private: int nextVowelIndex(const string &s, int index){ for(int i = index ; i < s.size() ; i ++) if(isVowel(s[i])) return i; return s.size(); } int preVowelIndex(const string &s, int index ){ for(int i = index ; i >= 0 ; i --) if(isVowel(s[i])) return i; return -1; } bool isVowel(char c){ char lowerc = tolower(c); return lowerc == 'a' || lowerc == 'e' || lowerc == 'i' || lowerc == 'o' || lowerc == 'u'; } };

    PYTHON 版本

    class Solution: def reverseVowels(self, s: str) -> str: s=list(s) vowels=['a','e','i','o','u'] left=0 right=len(s)-1 while left<=right: while left<=right and s[left].lower() not in vowels: left+=1 while left<=right and s[right].lower() not in vowels: right-=1 if left<=right: s[left],s[right]=s[right],s[left] left+=1 right-=1 return ''.join(s)
    最新回复(0)