简化路径
题目
给定一个文档(Unix-style)的完全路径,请进行路径简化。
样例
“/home/”, => “/home”
“/a/./b/../../c/”, => “/c”挑战
你是否考虑了 路径 = “/../” 的情况?
在这种情况下,你需返回”/”。
此外,路径中也可能包含双斜杠’/’,如 “/home//foo/”。
在这种情况下,可忽略多余的斜杠,返回 “/home/foo”。题解
先用split函数以”/”分隔字符串,遍历路径数组,遇到..表示返回上一层路径则进行出栈,遇到.表示当前路径不变则什么都不用做,遇到文件名则压栈。最后把栈中路径进行拼接。
public class Solution {
/**
* @param path the original path
* @return the simplified path
*/
public String simplifyPath(String path) {
String result = "/";
String[] arr = path.split("/");
ArrayList<String> paths = new ArrayList<String>();
for (String s : arr)
{
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;
}
}
Last Update 2016.11.17