LeetCode 345: Reverse Vowels of a String Solution
Master LeetCode problem 345 (Reverse Vowels of a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
345. Reverse Vowels of a String
Problem Explanation
Explanation:
To solve this problem, we can use a two-pointer approach where we maintain two pointers, one starting from the beginning of the string and the other starting from the end of the string. We iterate through the string while moving these pointers towards each other. When both pointers point to a vowel, we swap them. This way, we reverse only the vowels in the string.
- Time complexity: O(n) where n is the length of the input string.
- Space complexity: O(1) as we are using constant extra space.
Solution Code
class Solution {
public String reverseVowels(String s) {
char[] chars = s.toCharArray();
String vowels = "aeiouAEIOU";
int i = 0, j = s.length() - 1;
while (i < j) {
while (i < j && vowels.indexOf(chars[i]) == -1) {
i++;
}
while (i < j && vowels.indexOf(chars[j]) == -1) {
j--;
}
if (i < j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
i++;
j--;
}
}
return new String(chars);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 345 (Reverse Vowels of a String)?
This page provides optimized solutions for LeetCode problem 345 (Reverse Vowels of a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 345 (Reverse Vowels of a String)?
The time complexity for LeetCode 345 (Reverse Vowels of a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 345 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 345 in Java, C++, or Python.