Simplify Path

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

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

答案

粗暴解题法,自己分割string,调试很久才成功

class Solution {
    public String simplifyPath(String path) {
        if(path.equals("")) return "";
        
        Stack<String> stk = new Stack<String>();
        int left = 1, right = path.length() - 1, slash = 0;
        while(left <= right) {
            String token;
            int slash2 = path.indexOf('/', left);
            if(slash2 != -1) {
                token = path.substring(slash + 1, slash2);
                slash = slash2;
                left = slash2 + 1;
            } 
            else {
                token = path.substring(slash + 1);
                left = right + 1;
            }
            
            if(!token.equals("") && !token.equals(".")) {
                if(token.equals("..")) {
                    if(!stk.isEmpty())
                        stk.pop();                    
                }
                else {
                    stk.push(token);
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        if(stk.isEmpty()) return "/";
        while(!stk.isEmpty()) {
            sb.insert(0, "/" + stk.pop());
        }
        return sb.toString();
    }
}

用split函数

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stk = new Stack<String>();
        for(String token : path.split('/')) {
            if(token.equals("") || token.equals(".")) continue;
            if(token.equals(".."))
                if(!stk.isEmpty()) stk.pop();
            else
                stk.push(token);
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stk.isEmpty()) {
            sb.insert(0, "/" + stk.pop());
        }
        return sb.isEmpty()? "/" : sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。