LeetCode_Stack_Simplify Path

来源:互联网 发布:仿淘宝拖拽式模板系统 编辑:程序博客网 时间:2024/06/04 20:12

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
原创粉丝点击