Fast Java solution


  • 0
    public class Solution {
        public String simplifyPath(String path) {
            if(path == null || path.length() == 0) return path;
            char[] cs = path.toCharArray();
            int len = cs.length;
            Stack<String> stack = new Stack<String>();
            int i = 0;
            while(i < len){
                StringBuilder sb = new StringBuilder();
                sb.append('/');
                while(i < len && cs[i] != '/'){
                    sb.append(cs[i]);
                    ++i;
                }
                String s = sb.toString();
                if(s.equals("/..")){
                    if(!stack.empty()) stack.pop();
                }else if(s.length() > 1&&!s.equals("/.")){
                    stack.push(s);
                }
                ++i;
            }
            StringBuilder resSb = new StringBuilder();
            while(!stack.empty()){
                resSb.insert(0, stack.pop());
            }
            return resSb.length() == 0 ? "/" : resSb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.