345. Reverse Vowels Of A String¶
Difficulty: Easy
LeetCode Problem View on GitHub
345. Reverse Vowels of a String
Easy
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 * 105sconsist of printable ASCII characters.
Solution¶
class Solution {
public String reverseVowels(String s) {
int n = s.length();
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
char current = s.charAt(i);
if (isVowel(current)) res.add(i);
}
Collections.reverse(res);
int k = 0;
String ans = "";
for (int i = 0; i < n; i++) {
char current = s.charAt(i);
if (isVowel(current)) ans += s.charAt(res.get(k++));
else ans += current;
}
return ans;
}
private boolean isVowel(char current) {
if (current == 'a' || current == 'e' || current == 'i' || current == 'o' || current == 'u') return true;
if (current == 'A' || current == 'E' || current == 'I' || current == 'O' || current == 'U') return true;
return false;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here