345. Reverse Vowels of a String 【LeetCode】

题目描述

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”

刚开始暴力双重循环,然后超时

class Solution {
public:
    string reverseVowels(string s) {
        string str = "aeiouAEIOU",t=s;
        vector<int> v;
        int len1=0,len2=s.size()-1;
        while(len1<=len2)
        {
            while(str.find(s[len1])==string::npos)
                len1++;
            while(str.find(s[len2])==string::npos)
                len2--;
            char ch = s[len1];
            s[len1] = s[len2];
            s[len2] = ch;
        }
        return s;
    }
};

然后把元音字母下标存起来,改为单层循环,代码如下:

class Solution {
public:
    string reverseVowels(string s) {
        string str = "aeiouAEIOU",t=s;
        vector<int> v;
        int len1=0,len2=s.size()-1;
        for(int i = 0;i<s.size();i++)
        {
            if(str.find(s[i])!=string::npos)
                v.push_back(i);
        }
        for(int i = 0,j=v.size()-1;i<=j;i++,j--)
        {
            char ch = s[v[i]];
            s[v[i]] = s[v[j]];
            s[v[j]] = ch;
        }
        return s;
    }
};

猜你喜欢

转载自blog.csdn.net/hhhhhh5863/article/details/88956312