[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<String> stack = new Stack<String>();
        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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容