20.4.11 Reverse vowels in a string

Time complexity O (n), space complexity O (1)

topic

Write a function that takes a string as input and reverses the vowels in the string.

Example 1:
Input: "hello"
Output: "holle"

Example 2:
Input: "leetcode"
Output: "leotcede"

Problem solving, code ideas

1. Double pointer, the pointer begin scans the string from front to back. If a vowel character is found and it is not charged with the pointer end, begin points to the vowel character and stops scanning. The pointer end starts to scan the string from back to front. vowel and not begin to overlap with the pointer, end pointing to the vowel and stop scanning;
2, if begin is not equal to End, and the two vowel characters are not the same, the exchange;
3, 1,2 is repeated until two The pointer overlaps or the pointer begin behind the pointer end.

Code

class Solution {
public:
    string reverseVowels(string s) {
        if(s.length() == 0) return s;

        int begin = 0;
        int end = s.length() - 1;
        while(begin < end){
            while(s[begin] != 'a' && s[begin] != 'o' 
            && s[begin] != 'e' && s[begin] != 'i' 
            && s[begin] != 'u' && s[begin] != 'A' && s[begin] != 'O' 
            && s[begin] != 'E' && s[begin] != 'I' 
            && s[begin] != 'U' && begin < end) begin++;
            while(s[end] != 'a' && s[end] != 'o' 
            && s[end] != 'e' && s[end] != 'i' 
            && s[end] != 'u' && s[end] != 'A' && s[end] != 'O' 
            && s[end] != 'E' && s[end] != 'I' 
            && s[end] != 'U' && begin < end) end--;
            if(begin != end){
                if(s[begin] != s[end]){
                    int save = s[begin];
                    s[begin] = s[end];
                    s[end] = save;
                }
                begin++;
                end--;
            }
        }

        return s;
    }
};

Guess you like

Origin www.cnblogs.com/wasi-991017/p/12678534.html