Java solution without using built-in split function. Clean and easy to understand


  • 0

    ...

    public class Solution {
    public String simplifyPath(String path) {
    if (path == null || path.length() == 0 || !(path.charAt(0) == '/')) {
    return "/";
    }

    	Stack<String> stack = new Stack<String>();
    	String temp = null;
    
    	int i = 1;
    	int lastIndex = path.lastIndexOf('/');
    
    	for (int j = 1; j < path.length(); j++) {
    		if (path.charAt(j) == '/' || j > lastIndex) {
    
    			if (j > lastIndex) {
    				temp = path.substring(lastIndex + 1, path.length());
    			} else {
    				temp = path.substring(i, j);
    				i = j + 1;
    			}
    
    			if (temp.equals("") || temp.equals(".")) {
    				continue;
    			} else if (temp.equals("..")) {
    				if (!stack.isEmpty()) {
    					stack.pop();
    				}
    			} else {
    				stack.push(temp);
    			}
    
    			if (j > lastIndex) {
    				break;
    			}
    		}
    	}
    
    	if (stack.isEmpty()) {
    		return "/";
    	}
    
    	String simplifiedPath = "";
    	while (!stack.isEmpty()) {
    		simplifiedPath = "/" + stack.pop() + simplifiedPath;
    	}
    
    	return simplifiedPath;
    }
    

    }


Log in to reply
 

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