LeetCode-----71. Simplify Path(简化文件路径)

来源:互联网 发布:淘宝qq群优惠券靠谱吗 编辑:程序博客网 时间:2024/05/16 18:47

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

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

注意:/. //. //  /.. 等情况(可以考虑 栈 操作)

Input:"/abc/..."
Output:"/..."
Expected:"/abc/..."

字符串处理,由于".."是返回上级目录(如果是根目录则不处理),因此可以考虑用栈记录路径名,以便于处理。需要注意几个细节:

  1. 重复连续出现的'/',只按1个处理,即跳过重复连续出现的'/';
  2. 如果路径名是".",则不处理;
  3. 如果路径名是"..",则需要弹栈,如果栈为空,则不做处理;
  4. 如果路径名为其他字符串,入栈。

最后,再逐个取出栈中元素(即已保存的路径名),用'/'分隔并连接起来,不过要注意顺序呦。

public class Solution {    public String simplifyPath(String path) {        String result = "/";        String[] stubs = path.split("/+");        ArrayList<String> paths = new ArrayList<String>();        for (String s : stubs){            if(s.equals("..")){                if(paths.size() > 0){                    paths.remove(paths.size() - 1);                }            }            else if (!s.equals(".") && !s.equals("")){                paths.add(s);            }        }        for (String s : paths){            result += s + "/";        }        if (result.length() > 1)            result = result.substring(0, result.length() - 1);        return result;    }}


0 0
原创粉丝点击