둘셋 개발!

345. Reverse Vowels of a String - 문자열 본문

알고리즘

345. Reverse Vowels of a String - 문자열

23 2026. 4. 21. 23:30

🔆 문제 링크

https://leetcode.com/problems/reverse-vowels-of-a-string/description/?envType=study-plan-v2&envId=leetcode-75

 

Reverse Vowels of a String - LeetCode

Can you solve this real interview question? Reverse Vowels of a String - 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 onc

leetcode.com

 

☁️ 문제 해석

주어진 문자열에서 모음인 문자만 역순으로 재배치한다.

ex) IceCreAm -> AceCreIm


💡 접근 방법1

처음에는 stack을 생각했다.

문자열을 순차적으로 돌면서, 모음인 문자는 stack에 저장한다.

그리고 다시 문자열을 돌면서 모음인 위치에 stack에 꺼낸 값을 넣어준다.

하지만 이 해결방법에는 stack의 저장 공간이 따로 필요하다는 단점이 있다.

직관적으로 stack이 떠올랐지만, 이 방법은 최선이 아닌 듯 하다.

 

💡 접근 방법2

투 포인터를 이용한다.

첫번째 포인터는 앞에서 뒤로,  두번재 포인터는 뒤에서 앞으로 이동한다.

두 개의 포인터 모두 모음일때까지 이동시킨다.

그리고 서로 switch한다. 

이 과정을 서로의 포인터가 엇갈릴 때까지 반복한다.

 

🖥️ 코드

import java.util.Stack;

class Solution {
    public String reverseVowels(String s) {
        HashSet<Character> moumList = new HashSet<> ();
        moumList.add('a');
        moumList.add('e');
        moumList.add('i');
        moumList.add('o');
        moumList.add('u');
        moumList.add('A');
        moumList.add('E');
        moumList.add('I');
        moumList.add('O');
        moumList.add('U');
        StringBuilder sb = new StringBuilder(s);
        int startIndex = 0;
        int endIndex = s.length()-1;

        while (true) {

            while (startIndex<s.length()) {
                if (moumList.contains(sb.charAt(startIndex))) {
                    break;
                }
                startIndex++;
            }

            while (endIndex>=0) {
                if (moumList.contains(sb.charAt(endIndex))) {
                    break;
                }
                endIndex--;
            }
            
            if (startIndex>=endIndex) {
                break;
            }
            char temp = sb.charAt(startIndex);
            sb.setCharAt(startIndex++, sb.charAt(endIndex));
            sb.setCharAt(endIndex--, temp);
        }

        return sb.toString();
    }
}

 

  투 포인터를 사용할 때는 반복문 종료 조건을 먼저 생각하고 코드를 짜면 실수를 덜 하게 되는 것 같다.

이 코드는 startIndex가 endIndex보다 크거나 같으면 반복문이 종료된다.

 

📒 자바 문법 플러스

1. 제네릭 타입은 wrapper class만 담을 수 있다.

제네릭 타입은 컴파일 과정에서 Object 타입으로 변환하기 때문에 Object를 상속하는 Wrapper class만 담을 수 있다.

int, double, char 이런 원시 타입은 Object 타입으로 변환하지 못한다.

 

2. StringBuilder.setCharAt(위치, 새로운 문자)

setCharAt으로 원하는 위치에서 다른 문자로 수정할 수 있다.


🗺️ github 주소

https://github.com/janguni/leetcode/tree/main/0345-reverse-vowels-of-a-string