返回

[Leetcode]345. Reverse Vowels of a String(C++)

题目描述

题目链接:345. Reverse Vowels of a String

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

例子

例子 1

Input: “hello” Output: “holle”

例子 2

Input: “leetcode” Output: “leotcede”

Note

The vowels does not include the letter “y”.

解题思路

通过前后双指针分别向另一侧遍历,每遇到一对元音字符(写一个函数判断字符是否为元音,判断之前先转换大小写)即交换,这里注意遍历过程中一定要保证 前指针 < 后指针,代码如下:

#include <string>
#include <ctype.h>

class Solution {
public:
    std::string reverseVowels(std::string s) {
        int front = 0, back = s.length() - 1;
        while (front < back && !isVowel(s[front])) front++;
        while (front < back && !isVowel(s[back])) back--;
        while (front < back) {
            std::swap(s[front], s[back]);
            front++; back--;
            while (front < back && !isVowel(s[front])) front++;
            while (front < back && !isVowel(s[back])) back--;
        }
        return s;
    }

private:
    bool isVowel(char letter) {
        letter = tolower(letter);
        return (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u');
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy