leetcode

Sort Vowels in a String - Link

Question Description

Given a string s, sort only the vowels in ascending order and keep other characters in place.

Vowels are: ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (both lowercase and uppercase).


Constraints


Approach

Two approaches are provided:

Approach 1:

Approach 2:

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input: s = "lEetcOde"

Approach 2 Dry Run:

Final Answer = "lEOtcOde"


Solution

import java.util.*;

class Solution {

    // Approach 1
    public String sortVowelsApproach1(String s) {
        List<Character> vowels = new ArrayList<>();
        
        // Extract vowels
        for (char c : s.toCharArray()) {
            if ("AEIOUaeiou".indexOf(c) != -1) {
                vowels.add(c);
            }
        }

        // Sort vowels
        Collections.sort(vowels);

        // Rebuild string with sorted vowels
        StringBuilder result = new StringBuilder();
        int vIndex = 0;
        for (char c : s.toCharArray()) {
            if ("AEIOUaeiou".indexOf(c) != -1) {
                result.append(vowels.get(vIndex++));
            } else {
                result.append(c);
            }
        }

        return result.toString();
    }

    // Approach 2
    public String sortVowelsApproach2(String s) {
        Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
        List<Character> extractedVowels = new ArrayList<>();

        // Extract vowels
        for (char c : s.toCharArray()) {
            if (vowels.contains(c)) {
                extractedVowels.add(c);
            }
        }

        // Sort vowels
        Collections.sort(extractedVowels);

        // Rebuild string with sorted vowels
        StringBuilder sb = new StringBuilder();
        int index = 0;
        for (char c : s.toCharArray()) {
            if (vowels.contains(c)) {
                sb.append(extractedVowels.get(index++));
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }
}

Time and Space Complexity