Dare2Solve
The problem requires reversing only the vowels in a given string while keeping the positions of other characters unchanged. Vowels are defined as 'A', 'E', 'I', 'O', 'U' (both uppercase and lowercase).
To solve this problem, we can first identify all the vowels in the string, reverse their order, and then insert them back into their original positions. By iterating over the string twice, once to collect the vowels and another to replace them, we can achieve the desired result.
O(n), where n is the length of the string. The string is iterated over twice: once to collect vowels and once to replace them.
O(n) for storing the list of vowels.
class Solution {
public:
std::string reverseVowels(std::string s) {
std::string vowels = "AEIOUaeiou";
std::string vow = "";
for (char c : s) {
if (vowels.find(c) != std::string::npos) {
vow += c;
}
}
std::reverse(vow.begin(), vow.end());
int i = 0;
for (char& c : s) {
if (vowels.find(c) != std::string::npos) {
c = vow[i++];
}
}
return s;
}
};
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = "AEIOUaeiou"
vow = [c for c in s if c in vowels]
revStr = []
i = 0
for char in s:
if char in vowels:
revStr.append(vow.pop())
else:
revStr.append(char)
return ''.join(revStr)
class Solution {
public String reverseVowels(String s) {
String vowels = "AEIOUaeiou";
StringBuilder vow = new StringBuilder();
for (char c : s.toCharArray()) {
if (vowels.indexOf(c) != -1) {
vow.append(c);
}
}
vow.reverse();
StringBuilder revStr = new StringBuilder();
int i = 0;
for (char c : s.toCharArray()) {
if (vowels.indexOf(c) != -1) {
revStr.append(vow.charAt(i++));
} else {
revStr.append(c);
}
}
return revStr.toString();
}
}
var reverseVowels = function (s) {
let revStr = '', vowels = 'AEIOUaeiou', vow = '', i = 0
for (let char of s) {
if (vowels.includes(char)) {
vow += char
}
}
vow = vow.split('').reverse().join('')
for (let char of s) {
if (vowels.includes(char)) {
revStr += vow[i]
i++
} else {
revStr += char
}
}
return revStr
};