# 71 Simplify Path

Concept:

先搞懂縮短的規則,

多餘的/要去掉,

..表示回上一層,

.什麼事都不用做。

用stack來記錄最終路徑。

Pseudocode:

先把path用 /+ split開,存在String[] sp
create a stack to save all parent folders
create a stringbuilder sb to save answer
for each element in sp,
    if ".." stack.pop
    else if ".", continue
    else
        stack.push(sp[i])

while(stack is not empty)
    insert stack.pop to sb

return sb.toString()

Code:

實作時要注意的小地方:

  1. 在stack.pop前面要防止corner case(stack沒東西)
  2. 在組成字串時,要防止stack裡面有空字串
  3. corner case: stack裡沒東西,output為"/"
public class Solution {
    public String simplifyPath(String path) {

        String[] sp = path.split("/+");
        Deque<String> stack = new ArrayDeque<>();
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<sp.length; i++){
            if(sp[i].equals("..")){
                if(!stack.isEmpty())
                    stack.pop();
            }
            else if(sp[i].equals("."))
                continue;
            else{
                stack.push(sp[i]);
            }
        }

        while(!stack.isEmpty()){
            String s = stack.pop();
            if(!s.equals(""))
                s = "/"+s;
            sb.insert(0, s);
        }
        if(sb.toString().length() == 0)
            sb.append("/");
        return sb.toString();
    }
}

results matching ""

    No results matching ""