LeetCode*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:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

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

答案:

class Solution {
public:
    string reverseVowels(string s) {
        string sv = "aeiouAEIOU";
        int i = 0;
        int j = s.length() - 1;
        
        while (i < j) {
            /* std::string::npos Means => static const size_t npos = -1; */
            while ((sv.find(s[i]) == std::string::npos) && (i < j)) {
                i++;
            }
            while ((sv.find(s[j]) == std::string::npos) && (i < j)) {
                j--;
            }
            
            if ((s[i] != s[j]) && (i < j)) {
                swap(s[i], s[j]);
            }
            
            i++;
            j--;
        }
        return s;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容