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

For example,
path = “/home/”, => “/home”
path = “/a/./b/…/…/c/”, => “/c”
click to show corner cases.

思路:
首先将所有的内容从/中分离出来,然后分别处理。这里我们需要用到堆栈的数据结构。堆栈有很多种实现方式,java中的Stack类LinkedList类都可以实现其功能。我们将读到的路径入栈,根据操作符出栈,最后将栈中剩余的元素组织成String路径返回即可。

class Solution {
public String simplifyPath(String path) {
Stack<String> s = new Stack<String>();
String[] pathDetail = path.split("/");
for(int i = 0 ; i < pathDetail.length ; i++){
//弹出上级目录,如果有上级目录
if (pathDetail[i].equals("..")){
if (s.isEmpty()){
continue;
}
s.pop();
//不进行任何操作
} else if (pathDetail[i].equals(".") || pathDetail[i].isEmpty()){
continue;
} else {
s.push(pathDetail[i]);
}
}
if (s.isEmpty()){
return "/";
}
StringBuilder result = new StringBuilder();
do {
result.insert(0, s.pop());
result.insert(0, "/");
} while (!s.isEmpty());
return result.toString();
}
}
class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() < 1) return path;
Deque<String> deque = new LinkedList<String>();
int index = 0;
StringBuilder ans = new StringBuilder();
while(index < path.length()) {
if(path.charAt(index) != '/') {
StringBuilder dirName = new StringBuilder();
int dots = 0;
while(index < path.length() && path.charAt(index) != '/') {
dirName.append(path.charAt(index) + "");
if(path.charAt(index++) == '.') {
dots++;
} else dots = 0;
}
if(dirName.length() > 2 || dots == 0) deque.add(dirName.toString());
else if(dots == 2) if(!deque.isEmpty()) deque.removeLast();
}
while(index < path.length() && path.charAt(index) == '/') index++;
}
if(deque.isEmpty()) return "/";
while(!deque.isEmpty()) ans.append("/" + deque.removeFirst());
return ans.toString();
}
}
class Solution:
def simplifyPath(self, path: str) -> str:
lst = path.split('/')

stack = []

for x in lst:
if x in ['.','']:
continue
if x == '..':
if stack:
stack.pop()
else:
stack.append(x)

return '/' + '/'.join(stack)