Reverse Vowels of a String
LeetCode 345 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 = "IceCreAm"
Output: "AceCreIm"
Explanation:
The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
- `1 <= s.length <= 3 * 10^5`
- `s` consist of **printable ASCII** characters.
Topics: Two Pointers, String
Approachβ
Direct Approachβ
This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.
When to use
Basic problems that test fundamental programming skills.
Solutionsβ
Solution 1: C# (Best: 136 ms)β
| Metric | Value |
|---|---|
| Runtime | 136 ms |
| Memory | N/A |
| Date | 2018-04-05 |
Solution
public class Solution {
public string ReverseVowels(string s) {
char[] sArray = s.ToCharArray();
int len = s.Length;
if(String.IsNullOrEmpty(s) || len==1) return s;
int i=0, j=len-1;
while(i<j)
{
while(!IsVowel(sArray[i]) && i<j)
{
i++;
}
while(!IsVowel(sArray[j]) && i<j)
{
j--;
}
if(i<j)
{
char temp = sArray[i];
sArray[i] = sArray[j];
sArray[j] = temp;
}
i++;
j--;
}
return new string(sArray);
}
public bool IsVowel(char c)
{
char[] vowels = {'A','E','I','O','U','a','e','i','o','u'};
return vowels.Contains(c);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Two Pointers | $O(n)$ | $O(1)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.