[LeetCode 71] Simply Path (simple)

Given an absolute path for a file (Unix-style), simplify it.

Example

"/home/", => "/home"

"/a/./b/../../c/", => "/c"

Challenge

  • Did you consider the case where path ="/../"?
    In this case, you should return"/".

  • Another corner case is the path might contain multiple slashes '/'together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

思路

  1. 将整个路径按照/分开来
  2. 用一个栈来存路径,遇到..时弹出一个,遇到.空字符串则不变,遇到正常路径则压入栈中。

Note

  1. 如果结果为空,返回/
  2. 弹出栈时要先检查栈是否为空
public class Solution {
    
    /*
     * @param path: the original path
     * @return: the simplified path
     */
    public String simplifyPath(String path) {
        // write your code here
        //用stack来存通过split(“ ”)分离的path
        //有四种情况,
        // “.”:什么都不做
        // “..”:退回上一层
        // “”:什么都不做
        //其他字符:入栈
        
        Stack stack = new Stack();
        String[] strList = path.split("/");
        StringBuilder result = new StringBuilder();
        
        for(String curStr : strList) {
            if (curStr.equals(".")) {
                continue;
            } else if (curStr.equals("")) {
                continue;
            } else if (curStr.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                    continue;
                }
            } else {
                stack.push(curStr);
            }
        }
        
        //如果为空,则返回空地址
        if (stack.isEmpty()) {
            return "/";
        }
        
        //不为空,从后向前加result
        while (!stack.isEmpty()) {
            result.insert(0,"/"+stack.pop());
        }
        
        return result.toString();
    }
}

你可能感兴趣的:([LeetCode 71] Simply Path (simple))