Share my 8ms Java solution


  • 9
    S
    public String simplifyPath(String path) {
    	String[] dir = path.split("/");
    	String[] stack = new String[dir.length];
    	int ptr = 0;
    	for(int i = 0; i < dir.length; i++){
    		if(dir[i].equals(".") || dir[i].equals("")){
    			continue;
    		}else if(dir[i].equals("..")){
    			if(ptr > 0) ptr--;
    		}else{
    			stack[ptr] = dir[i];
    			ptr++;
    		}
    	}
    	StringBuilder result = new StringBuilder();
    	for(int i = 0; i < ptr; i++){
    		result.append("/");
    		result.append(stack[i]);
    	}
    	return result.length() == 0 ? "/" : result.toString();
    }

  • 0
    S

    nearly :)

    public class Solution {
        public String simplifyPath(String path) {
            char[] paths = (path+'/').toCharArray();
            StringBuilder sb = new StringBuilder();
            List<String> list = new LinkedList<>();
            for(char c : paths) {
                if(c != '/') {
                    sb.append(c);
                } else if (sb.length() != 0){
                    String test = sb.toString();
                    if(test.equals("..")) {
                        if(list.size() != 0) list.remove(list.size()-1);
                    } else if(!test.equals(".")){
                        list.add(test);
                    }
                    sb.delete(0, sb.length());
                }
            }
            for(String p : list) {
                sb.append('/');
                sb.append(p);
            }
            if(sb.length() == 0) return "/";
            return sb.toString();
        }
    }
    

Log in to reply
 

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