标签:
问题描述
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
"/../"?"/".‘/‘ together, such as "/home//foo/"."/home/foo".解决思路
双端队列(LinkedList).
程序
public class Solution {
public String simplifyPath(String path) {
if (path == null || path.trim().length() == 0) {
return "";
}
String[] splits = path.split("/");
LinkedList<String> ll = new LinkedList<String>();
for (int i = 0; i < splits.length; i++) {
String spl = splits[i];
if (spl.trim().length() == 0) {
continue;
}
if (spl.equals(".")) {
continue;
}
if (spl.equals("..")) {
if (!ll.isEmpty()) {
ll.removeLast();
}
continue;
}
ll.add(spl.trim());
}
if (ll.isEmpty()) {
return "/";
}
StringBuilder sb = new StringBuilder();
while (!ll.isEmpty()) {
sb.append("/" + ll.removeFirst());
}
return sb.toString();
}
}
附上测试用例
String[] paths = { "/home/", "/a/./b/../../c/", "/../", "/home//foo/",
"/home/foo/.ssh/../.ssh2/authorized_keys/" };
Output
path:/home/ | /home
path:/a/./b/../../c/ | /c
path:/../ | /
path:/home//foo/ | /home/foo
path:/home/foo/.ssh/../.ssh2/authorized_keys/ | /home/foo/.ssh2/authorized_keys
标签:
原文地址:http://www.cnblogs.com/harrygogo/p/4739543.html