Simplify Path——LeetCode

2890 단어 LeetCode
Given an absolute path for a file (Unix-style), simplify it.
For example,path =  "/home/" , =>  "/home" path =  "/a/./b/../../c/" , =>  "/c"
 
제목: String 에 파일 의 절대 경 로 를 표시 하고 간소화 합 니 다.
문제 풀이 방향: 하나의 스 택 으로 표시 하면 됩 니 다.........................................................................
public class Solution {

    public String simplifyPath(String path) {

        if (path == null || path.length() == 0) {

            return null;

        }

        Deque<String> deque = new ArrayDeque<>();

        String[] dirs = path.split("/");

        for (String dir : dirs) {

            if (".".equals(dir)){

                continue;

            }

            else if ("..".equals(dir)) {

                if (!deque.isEmpty()) {

                    deque.pop();

                }

            } else {

                if(dir==null||dir.length()==0){

                    continue;

                }

                deque.push(dir);

            }

        }

        String res = "/";

        while (!deque.isEmpty()) {

            res += deque.pollLast();

            res += "/";

        }

        res = res.substring(0, res.length() > 1 ? res.length() - 1 : 1);

        return res;

    }

}

좋은 웹페이지 즐겨찾기