Easy to understand Java Solution(16 ms)


  • 2
    T
    public class Solution {
        public String simplifyPath(String path) {
            String[] ar = path.split("\\/+");
            ArrayList<String> st = new ArrayList();
            for(String s : ar){
                switch(s){
                   case "": 
                   case "." : continue;
                   case "..":
                       if(st.size()>0)st.remove(st.size()-1);
                       break;
                   default:
                        st.add(s);
                        break;
                }
            }
            if(st.size()==0)return "/";
            StringBuilder sb = new StringBuilder();
            for(String s : st){
                sb.append("/");
                sb.append(s);
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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