Leetcode 71. Simplify Path

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();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值