LeetCode 2785: Sort Vowels in a String Solution
Master LeetCode problem 2785 (Sort Vowels in a String), a medium 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.
Problem Explanation
Explanation:
- We will iterate through the input string
sand separate the vowels and consonants. - Sort the vowels in non-decreasing order of their ASCII values.
- Iterate through the string
sagain and replace the vowels with the sorted vowels while keeping the consonants in their original positions.
Time Complexity: O(nlogn) where n is the length of the input string s
Space Complexity: O(n) where n is the length of the input string s
Solution Code
import java.util.Arrays;
class Solution {
public String sortVowelsInString(String s) {
char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
boolean[] isVowel = new boolean[256];
for (char c : vowels) {
isVowel[c] = true;
}
char[] sortedVowels = s.chars()
.filter(c -> isVowel[c])
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString()
.toCharArray();
int vIndex = 0;
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
if (isVowel[c]) {
result.append(sortedVowels[vIndex++]);
} else {
result.append(c);
}
}
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2785 (Sort Vowels in a String)?
This page provides optimized solutions for LeetCode problem 2785 (Sort Vowels in 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 2785 (Sort Vowels in a String)?
The time complexity for LeetCode 2785 (Sort Vowels in 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 2785 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2785 in Java, C++, or Python.