Simplify Path

来源:互联网 发布:炒外汇模拟软件 编辑:程序博客网 时间:2024/06/06 01:25

1.题目

给定一个文档(Unix-style)的完全路径,请进行路径简化。

"/home/", => "/home"

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

2.算法

维护一个栈,对于每一个块(以‘/’作为分界)进行分析,如果遇到‘../’则表示要上一层,那么就是进行出栈操作,如果遇到‘./’则是停留当前,直接跳过,其他文件路径则直接进栈即可

    public String simplifyPath(String path)    {        // Write your code here    if (path == null || path.length() == 0)    {    return "";    }    LinkedList<String> stack = new LinkedList<String>();    StringBuilder res = new StringBuilder();    int i = 0;    while (i < path.length())    {    int index = i;    StringBuilder temp = new StringBuilder();    while (i < path.length() && path.charAt(i) != '/')    {    temp.append(path.charAt(i));    i++;    }    if (index != i)    {    String str = temp.toString();    if (str.equals(".."))    {    if (!stack.isEmpty())    {    stack.pop();    }    }    else if (!str.equals("."))    {    stack.push(str);    }    }    i++;    }    if (!stack.isEmpty())    {    String[] strs = stack.toArray(new String[stack.size()]);    for (int j = strs.length - 1; j >= 0; j--)    {    res.append("/" + strs[j]);    }    }    if (res.length() == 0)    {    res.append("/");    }    return res.toString();    }


0 0
原创粉丝点击