[LeetCode] Remove All Adjacent Duplicates In String

아르당·2026년 3월 28일

LeetCode

목록 보기
227/263
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

영어 소문자로 구성된 문자열 s가 주어진다. 중복 제거는 입접하고 동일한 두 글자를 선택해서 제거하는 과정이다.
s에서 중복되는 요소를 더 이상 제거할 수 없을 때까지 반복해서 제거한다.
모드 중복 제거가 끝나고 최종 문자열을 반환해라. 이 결과는 유일함을 증명할 수 있다.

Example

#1
Input: s = "abbaca"
Output: "ca"

#2
Input: s = "azxxzy"
Output: "ay"

Constraints

  • 1 <= s.length <= 10^5
  • s는 영어 소문자로 구성된다.

Solved

class Solution {
    public String removeDuplicates(String s) {
        StringBuilder sb = new StringBuilder();

        for(char c : s.toCharArray()){
            int l = sb.length();

            if(l > 0 && sb.charAt(l - 1) == c){
                sb.deleteCharAt(l - 1);
            }else{
                sb.append(c);
            }
        }

        return sb.toString();
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글