[코테 풀이] Clear Digits

시내·2024년 7월 4일

Q_3174) Clear Digits

출처 : https://leetcode.com/problems/clear-digits/

You are given a string s.

Your task is to remove all digits by doing this operation repeatedly:

Delete the first digit and the closest non-digit character to its left.
Return the resulting string after removing all digits.

class Solution {
    public String clearDigits(String s) {
        boolean[] removed = new boolean[s.length()];
        String answer = "";
        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i))) {
                removed[i] = true;
                for (int j = i - 1; j >= 0; j--) {
                    if (!removed[j] && !Character.isDigit(s.charAt(j))) {
                        removed[j] = true;
                        break;
                    }
                }
            }
        }
        for (int r = 0; r < removed.length; r++) {
            if (!removed[r]) answer += Character.toString(s.charAt(r));
        }
        return answer;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글