Leetcode 71. Simplify Path

来源:互联网 发布:网络教育怎么上课 编辑:程序博客网 时间:2024/06/05 13:27

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

So why we need to change the format of the String address. cause the format of the string address given is not a standard

format, so we need to turn it into a standard format.

The address string is split by some string, then we need to use this string array to construct the result..

There are different condition 

1 if the string array is '.' or '' that means that the the length of the string is 0, then just 

continue, 

2 if the string splited is '..', then if the stack is not empty, then just pop the stack.

3 if the string is not the case above, then just push the string into the stack.

4 and then pop the string in the stack in the order and construct the final result.

the only way I know is to append the poped string to the end of the result string.w

public class Solution {    public String simplifyPath(String path) {        if(path == null || path.length() == 0)            return path;        Stack<String>stack = new Stack<String>();        String[] temRes = path.split("/");        for(int i = 0; i < temRes.length; i++){            if(temRes[i].equals(".") || temRes[i].length() == 0)                 continue;            else if(temRes[i].equals("..")){                if(!stack.isEmpty()){                    stack.pop();                }            }            else{                stack.push(temRes[i]);            }        }        //I use two stack to reverse the make the order of the string the same with the original string        Stack<String> reverse = new Stack<String>();        StringBuffer result = new StringBuffer();        while(!stack.isEmpty()){            reverse.push(stack.pop());        }        while(!reverse.isEmpty()){            result.append("/" + reverse.pop());        }        if(result.length() == 0)            result.append("/");        return result.toString();    }}


0 0
原创粉丝点击