LeetCode:345. Reverse Vowels of a String

051103

题目

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"

我的解题思路
这道题跟LeetCode: 344. Reverse String思路差不多,主要是多了个判断当前要交换的字符是不是元音字母,如果是的话才交换,否则一直往前走。不过,这里是用枚举的方式来判断是不是元音,这样其实有点繁琐。

class Solution {
public:
    string reverseVowels(string s) {
        int head=0, tail=s.size()-1;
        while(head<tail){
            if((s[head]=='a' || s[head]=='e' || s[head]=='i' || s[head]=='o' || s[head]=='u' || s[head]=='A' || s[head]=='E' || s[head]=='I' || s[head]=='O' || s[head]=='U') && (s[tail]=='a' || s[tail]=='e' || s[tail]=='i' || s[tail]=='o' || s[tail]=='u' || s[tail]=='A' || s[tail]=='E' || s[tail]=='I' || s[tail]=='O' || s[tail]=='U')){
                swap(s[head],s[tail]);
                head+=1;
                tail-=1;
            } 
            if(s[head]!='a' && s[head]!='e' && s[head]!='i' && s[head]!='o' && s[head]!='u' && s[head]!='A' && s[head]!='E' && s[head]!='I' && s[head]!='O' && s[head]!='U') head+=1;
            
            if(s[tail]!='a' && s[tail]!='e' && s[tail]!='i' && s[tail]!='o' && s[tail]!='u' && s[tail]!='A' && s[tail]!='E' && s[tail]!='I' && s[tail]!='O' && s[tail]!='U') tail-=1;
        }  
        return s;
    }
};

先来个改进版:把判断是否为元音字母封装为一个函数,再仿照LeetCode: 58. Length of Last Word
的写法。

public:
    string reverseVowels(string s) {
        int i = 0, j = s.length()-1;
        while(i<j) {
            while(i<j && !isVowel(s[i])) i++;
            while(i<j && !isVowel(s[j])) j--;
            if(i<j) swap(s[i++], s[j--]);
        }
        return s;
    }
private:
    bool isVowel(char c) const{
        return c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || 
            c=='A' || c=='E' || c=='I' || c=='O' || c=='U';
    }

看到没,这才是真正的大佬!

class Solution {
public:
    string reverseVowels(string s) {
        int i = 0, j = s.size() - 1;
        while (i < j) {
            i = s.find_first_of("aeiouAEIOU", i);
            j = s.find_last_of("aeiouAEIOU", j);
            if (i < j) {
                swap(s[i++], s[j--]);
            }
        }
        return s;
    }
};

s.find_first_of(“aeiouAEIOU”, i);这个函数意思是从s[i]开始向后去搜索"aeiouAEIOU"任意一个字符出现的第一个位置。s.find_last_of(“aeiouAEIOU”, j);意思是从s[j]开始向前去搜索"aeiouAEIOU"任意一个字符出现的最后一个位置。

猜你喜欢

转载自blog.csdn.net/liveway6/article/details/90106735