|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Judie 于 2023-6-1 22:22 编辑
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "hello"
Output: "hole"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 105
s consist of printable ASCII characters.
Judy
Python
- class Solution(object):
- def reverseVowels(self, s):
- """
- :type s: str
- :rtype: str
- """
- slst= list(s)
- vowels = 'aeiouAEIOU'
- lst = []
- for index, item in enumerate(s):
- if vowels.count(item) > 0:
- lst.append([index, item])
- for index, item in enumerate(lst):
- slst[item[0]] = lst[-(index+1)][1]
- return ''.join(slst)
复制代码
Mike
C++ slightly faster
- class Solution {
- public:
- bool isVowel(char c) {
- return (c == 'a' c == 'e' c == 'i' c == 'o' c == 'u' c == 'A' c == 'E' c == 'I' c == 'O' || c == 'U');
- }
- string reverseVowels(string s) {
- string str = s;
- int front = 0;
- int back = s.length() - 1;
- while (back > front) {
- while (!isVowel(s[front]) && front < back) {
- front++;
- }
- while (!isVowel(s[back]) && front < back) {
- back--;
- }
- str[front] = s[back];
- str[back] = s[front];
- front++;
- back--;
- }
- return str;
- }
- };
复制代码
Gray
C++ stack version
- class Solution {
- public:
- string reverseVowels(string s) {
- vector<int> vowel_index;
- stack<char> vowel_array;
- for(int i = 0; i < s.size();i++){
- if(tolower(s[i]) == 'a' tolower(s[i]) == 'e' tolower(s[i]) == 'i' tolower(s[i]) == 'o' tolower(s[i]) == 'u'){
- vowel_index.push_back(i);
- vowel_array.push(s[i]);
- }
- }
- for(int i = 0; i < vowel_index.size(); i++) {
- s[vowel_index[i]] = vowel_array.top();
- vowel_array.pop();
- }
- return s;
- }
- };
复制代码 |
|