Programming

Leetcode-71. Simplify Path

Leetcode-71. Simplify Path

Given a string path, which is an absolute path (starting with a slash ‘/’) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period ‘.’ refers to the current directory, a double period ‘..’ refers to the directory up a level, and any multiple consecutive slashes (i.e. ‘//’) are treated as a single slash ‘/’. For this problem, any other format of periods such as ‘…’ are treated as file/directory names.

The canonical path should have the following format:

The path starts with a single slash ‘/’. Any two directories are separated by a single slash ‘/’. The path does not end with a trailing ‘/’. The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period ‘.’ or double period ‘..’) Return the simplified canonical path.

Example 1:

Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

<解題>

1. 用Stack


class Solution {
    public String simplifyPath(String path) {
        Deque<String> stack = new LinkedList<>();
        Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));
        
        StringBuilder sb = new StringBuilder();
        String[] dirs = path.split("/");
        
        for (String dir : dirs) {
            if (dir.equals("..") && !stack.isEmpty()) {
                stack.pop();
            } else if (!skip.contains(dir)) {
                stack.push(dir);
            }
        }
        
        while (!stack.isEmpty()) {
            sb.insert(0, "/" + stack.pop());
        }
        
        return sb.length() == 0 ? "/" : sb.toString();
    }
}

2. 用使用兩個指針i和prevSlash來遍歷路徑的每個字符


class Solution {
    public String simplifyPath(String path) {
        StringBuilder sb = new StringBuilder();
        int n = path.length();
        int i = 0;
        
        while (i < n) {
            // 跳過多餘的斜線
            while (i < n && path.charAt(i) == '/') {
                i++;
            }
            
            // 構建當前目錄名稱
            StringBuilder curr = new StringBuilder();
            while (i < n && path.charAt(i) != '/') {
                curr.append(path.charAt(i));
                i++;
            }
            String dir = curr.toString();
            
            // 處理目錄名稱
            if (dir.equals("..")) {
                if (sb.length() > 0) {
                    int prevSlash = sb.lastIndexOf("/");
                    sb.delete(prevSlash, sb.length());
                }
            } else if (!dir.equals(".") && !dir.isEmpty()) {
                sb.append("/").append(dir);
            }
        }
        
        return sb.length() == 0 ? "/" : sb.toString();
    }
}

Time: O(n) Space: O(m)