[LeetCode / Easy] 345. Reverse Vowels of a String (Java)

이하얀·2025년 2월 2일
0

📙 LeetCode

목록 보기
7/13

💬 Info



Problem

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 once.



Example

예시 1

  • Input: s = "IceCreAm"
  • Output: "AceCreIm"
  • Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

예시 2

  • Input: s = "leetcode"
  • Output: "leotcede"

Constraints

  • 1 <= s.length <= 3 * 10510^5
  • s consist of printable ASCII characters.


문제 이해

  • 모음(a, e, i, o, u)를 찾으면 순서를 반대로 뒤집기


알고리즘

풀이 시간 : 분

  • 투 포인터를 i, j로 설정(양 끝에서 시작하는 방식)
  • 모음을 포함한 대문자 찾기
    • i는 왼 -> 오, j는 오 -> 왼
  • 모음이면 교환 + 포인터 이동
import java.util.*;

class Solution {
    public String reverseVowels(String s) {
        char[] str = s.toCharArray();
        Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
        
        int i = 0, j = str.length - 1;
        while (i < j) {
            while (i < j && !vowels.contains(str[i])) i++;
            while (i < j && !vowels.contains(str[j])) j--;
            
            char temp = str[i];
            str[i] = str[j];
            str[j] = temp;

            i++;
            j--;
        }
        return new String(str);
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글