Formatted question description:

71	Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.

Corner Cases:
    Did you consider the case where path = "/../"?
        In this case, you should return "/".
    Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
        In this case, you should ignore redundant slashes and return "/home/foo".



According to the example given in the title, it is really not easy to summarize the rules. Two more examples should be added path = "/a/./b/../c/", => "/a/c" and path = "/a/./b/c/", => "/a/b/c".

We can know the “.” in the middle and delete it directly, and delete it when it is “..” path next to it, and in some cases given by the following boundary conditions, it can be known that if it is empty, “/” is returned, and if there are multiple “/”, only one is retained. Then we can take the path as a number of substrings separated by one or more “/”, and extract them one by one.



import java.util.Stack;

public class Simplify_Path {

	public class Solution {
	    public String simplifyPath(String path) {

	        if (path == null || path.length() == 0) {
	            return path;

	        String result = "";

	        String[] array = path.split("/");
	        Stack<String> sk = new Stack<>();

	        int i = 0;
	        while (i < array.length) {

	            if (array[i].equals("..")) {
	                if (!sk.isEmpty()) {
	            } else if (!array[i].equals(".") && !array[i].equals("")) {


	        // @note: I missed this one
	        if (sk.isEmpty())   return "/";

	        while (!sk.isEmpty()) {
	            result = "/" + sk.pop() + result;

	        return result;


All Problems

All Solutions