inblog logo
|
stupefyee
    알고리즘문제풀기

    [JAVA 문제 풀이] 390. Delete Characters to Make Fancy String

    [멋진 문자열을 만들려면 문자 삭제하기]
    Stupefyee's avatar
    Stupefyee
    Jul 21, 2025
    [JAVA 문제 풀이] 390. Delete Characters to Make Fancy String
    Contents
    내가 작성한 코드다른 사람의 코드
    Delete Characters to Make Fancy String - LeetCode
    Can you solve this real interview question? Delete Characters to Make Fancy String - 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.   Example 1: Input: s = "leeetcode" Output: "leetcode" Explanation: Remove an 'e' from the first group of 'e's to create "leetcode". No three consecutive characters are equal, so return "leetcode". Example 2: Input: s = "aaabaaaa" Output: "aabaa" Explanation: Remove an 'a' from the first group of 'a's to create "aabaaaa". Remove two 'a's from the second group of 'a's to create "aabaa". No three consecutive characters are equal, so return "aabaa". Example 3: Input: s = "aab" Output: "aab" Explanation: No three consecutive characters are equal, so return "aab".   Constraints: * 1 <= s.length <= 105 * s consists only of lowercase English letters.
    Delete Characters to Make Fancy String - LeetCode
    https://leetcode.com/problems/delete-characters-to-make-fancy-string/description/
    Delete Characters to Make Fancy String - LeetCode
    notion image
    notion image
    화려한 문자열은 연속된 세 글자가 동일하지 않은 문자열입니다. 문자열 's'가 주어지면 's'에서 가능한 최소 문자 수를 삭제하여 화려하게 만드세요. 삭제 후 마지막 문자열을 반환합니다. 답변은 항상 고유하다는 것을 알 수 있습니다. 제약 조건: * 1 <= s.length <= 105 * s는 소문자 영어로만 구성되어 있습니다.
     

    내가 작성한 코드

    class Solution { public String makeFancyString(String s) { StringBuilder sb = new StringBuilder(); int count = 1; // 같은 문자열 수 카운트 변수 boolean isRepeated = false; // 문자열 반복 확인 변수 sb.append(s.charAt(0)); // 첫 글자 담아두기 for (int i = 1; i < s.length(); i++) { // 다른 문자열이 나올 경우 if (s.charAt(i) != s.charAt(i - 1)) { count = 1; isRepeated = false; } // 반복된 문자열이 나올 경우 if (isRepeated) { continue; } sb.append(s.charAt(i)); // 다음 글자 담아두기 // 문자열이 같은 경우 if (s.charAt(i) == s.charAt(i - 1)) { count++; // 같음 카운트 증가 if (count == 3) { count = 1; // 3개 이상이면 카운트 리셋 sb.deleteCharAt(sb.length() - 1); // 반복된 글자 제거 isRepeated = true; // 반복 문자열 확인 continue; } } } return sb.toString(); } }
     

    다른 사람의 코드

    class Solution { public String makeFancyString(String s) { int n = s.length(); StringBuilder ans = new StringBuilder(); int count = 1; // 카운트 for (int i = 0; i < n; i++) { // 문자열이 같은 경우 >> 카운트 증가 if (i > 0 && s.charAt(i) == s.charAt(i - 1)) { count++; } else { // 문자열이 다른 경우 >> 카운트 리셋 count = 1; } // 두번 이하로 반복된 경우 문자열 추가 if (count <= 2) { ans.append(s.charAt(i)); } } return ans.toString(); } }
     
    Share article
    Contents
    내가 작성한 코드다른 사람의 코드

    stupefyee

    RSS·Powered by Inblog