Backspace Compare: Character ArrayList

Jay·2022년 6월 1일
0

Grind 120

목록 보기
28/38
post-thumbnail


First Thoughts: the function of "#" is removing a character (if there are pre-existing characters in the list). We can add to a list of characters as we traverse, and remove as we meet the "#" symbol. The final return string is the combination of the character list.

My Solution:

        ArrayList<Character> chars = new ArrayList<>();
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i)=='#') {
                if (chars.isEmpty()) continue;
                else chars.remove(chars.size()-1);
            }
            else chars.add(s.charAt(i));
        }
        String str = "";
        for (char c: chars) str += c;

0개의 댓글