Simplify Path - LeetCode

 

주어진 경로를 정리하는 문제이다.

특이점은 ‘.’과 ‘..’의 처리이다. 주어진 경로를 ‘/’를 기준으로 나누고 Deque를 사용해서 처리하면 될 것이다.

  1. 문자열을 ‘/’로 분할한다.
  2. Deque에 문자를 넣는다.
  3. 이때 처리할 문자가 ‘..’이라면 Deque이 비어있지 않다면 한 번 pop을 한다.
  4. 문자가 ‘.’ 이라면 별도 처리를 하지 않는다.
  5. 모든 작업이 끝난 뒤 ‘/’를 넣어가며 Deque의 문자들을 앞에서부터 꺼내 완성한다.
class Solution {

    static final String PARENT = "..";
    static final String CURRENT = ".";
    static final String DELIMITER = "/";

    public String simplifyPath(String path) {
        Deque<String> stack = new ArrayDeque<>();
        for (String s : path.split("/")) {
            if (s.isEmpty()) continue;
            if (s.equals(PARENT)) {
                if (!stack.isEmpty()) {
                    stack.pollLast();
                }
            } else if (s.equals(CURRENT)) {
                continue;
            } else {
                stack.addLast(s);
            }

        }
        StringBuilder sb = new StringBuilder();
        sb.append(DELIMITER);
        while (!stack.isEmpty()) {
            String s = stack.pollFirst();
            sb.append(s).append(DELIMITER);
        }
        if (sb.length() != 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        
        return sb.toString();
    }
}

+ Recent posts