LeetCode_Stack_Simplify Path

71. Simplify Path

这里写图片描述


1. 问题描述:

输入一个目录String,要求简化目录并返回。

2. 解决思路:

题目需要仔细阅读,要求简化路径。所以有几种情况,需要分情况讨论:

  1. /./ 不做任何目录操作
  2. /../ 跳到上一级目录
  3. // 不做任何目录操作

这里我们使用stack存储目录名,然后遇到操作符号 ‘/./’,’/../’,’//’,做相应操作,具体看代码。

3. java代码:

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

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

        String[] pathList = path.split("/");
        String result = "";
        Stack<String> stack = new Stack<String>();

        for(int i=0;i<pathList.length;i++){
            if(pathList[i].equals(".")|| pathList[i].length()==0) {
                continue;
            } else if(pathList[i].equals("..")) {
                if(!stack.empty()){
                    stack.pop();
                }
            } else { 
                stack.push(pathList[i]); 
            }
        }

        for(int j=0;j<stack.size();j++){
            result +="/"+stack.get(j);
        }
        return result=="" ? "/" : result; 
    }
}

4. 算法评估:

这里写图片描述


希望多多指正交流!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值