A Java 7ms solution (93%)


  • 0
    L
    public String simplifyPath(String path) {
        List<String> strs = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < path.length(); i++){
            char ch = path.charAt(i);
            if(ch != '/') sb.append(ch);
            else{
                if(sb.length() == 0) continue;
                else if(sb.toString().equals("..")){
                    if(strs.size() > 0) strs.remove(strs.size() - 1);
                }else if (!sb.toString().equals(".")){
                    strs.add(sb.toString());
                }
                sb.setLength(0);
            }
        }
        if(sb.toString().equals("..")){
            if(strs.size() > 0) strs.remove(strs.size() - 1);
        }else if(sb.length() > 0 && !sb.toString().equals("."))
            strs.add(sb.toString());
        sb.setLength(0);
        sb.append('/');
        for(int i = 0; i < strs.size(); i++){
            sb.append(strs.get(i));
            if(i < strs.size() - 1) sb.append('/');
        }
        return sb.toString();
    }

Log in to reply
 

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