알고리즘

2024 11 04 1957. Delete Characters to Make Fancy String

물빠진떡 2024. 11. 1. 14:58

문제

A fancy string is a string where no three consecutive characters are equal.

Given a string s, delete the minimum possible number of characters from s to make it fancy.

Return the final string after the deletion. It can be shown that the answer will always be unique.

요약

String에서 연속으로 같은 char 3개가 나오지않게 제거

풀이

char를 하나씩 조회하면서 counting 하며 3개 이상이 되면 무시, 다른 글자가 나올 경우 count를 초기화하고 진행

코드

class Solution {
    public String makeFancyString(String s) {
        StringBuilder result = new StringBuilder();
        result.append(s.charAt(0));
        int count = 1;
        for (int i = 1; i < s.length(); i ++) {
            char c = s.charAt(i);
            if (result.charAt(result.length() - 1) != c) {
                count = 0;
            }
            if (count > 1) {
                continue;
            }
            result.append(c);
            count ++;
        }
        return result.toString();
    }
}

풀이 시간

5분

체감 난이도

easy