345. Reverse Vowels of a String
1. Description
Write a function that takes a string as input and reverse only the vowels of a string.
2. Example
Example 1:
Input: “hello”
Output: “holle”
Example 2:
Input: “leetcode”
Output: “leotcede”
3. Note
- The vowels does not include the letter “y”.
4. Solutions
My Accepted Solution
n = m_str.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
private:
bool isVowel(char letter)
{
letter = tolower(letter);
return (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u');
}
public:
// string reverseVowels(string s)
string reverseVowels(string &m_str)
{
for(int left = 0, right = m_str.size() - 1; left < right; left++, right--)
{
while(left < right && !isVowel(m_str[left])) left++;
while(left < right && !isVowel(m_str[right])) right--;
swap(m_str[left], m_str[right]);
}
return m_str;
}
};