[Leetcode] Simplify Path

来源:互联网 发布:法律法规数据库系统 编辑:程序博客网 时间:2024/06/10 13:04

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".
public class Solution {    public String simplifyPath(String path) {        Stack<String> result = new Stack<>();        StringBuilder simplifiedPath = new StringBuilder();        int lastSlash = 0;        String element = "";        for(int i = 1; i < path.length(); i++) {            if(path.charAt(i) == '/') {                element = path.substring(lastSlash + 1, i);                lastSlash = i;            }            else if(i == path.length() - 1) {                element = path.substring(lastSlash + 1, path.length());            }            else {                continue;            }                        if(element.equals(".") || element.equals("")){                continue;            }            else if(element.equals("..") ){                if(!result.empty()){                    result.pop();                }            }            else if(element.equals("/")){                result.clear();            }            else {                result.push(element);            }        }                if(result.empty()){            simplifiedPath.append("/");        }        else{            for(String pathEle : result) {                simplifiedPath.append("/").append(pathEle);            }        }        return simplifiedPath.toString();    }}


0 0