您的位置:首页 > 其它

[LeetCode] Simplify Path

2013-11-03 14:29 274 查看
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.

Corner Cases:

Did you consider the case where path = 
"/../"
?

In this case, you should return 
"/"
.
Another corner case is the path might contain multiple slashes 
'/'
 together,
such as 
"/home//foo/"
.

In this case, you should ignore redundant slashes and return 
"/home/foo"
.

核心思想很简单,使用一个栈在内容为“..”的时候弹出前一个元素即可。这题可以偷懒,使用一个StringTokenizer类,这样的话可以很快的形成一个过滤掉所有斜杠后的内容栈。

public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
StringBuffer strBuffer = new StringBuffer();

StringTokenizer st = new StringTokenizer(path, "/");
while (st.hasMoreTokens()) {
String str = st.nextToken();

// ignore "."
if (".".equals(str)) {
continue;
}
// pop out the last element
else if ("..".equals(str)) {
if (!stack.isEmpty())
stack.pop();
}
// push the current element
else {
stack.push(str);
}

}

if (stack.isEmpty())
strBuffer.append("/");

while (!stack.isEmpty()) {
strBuffer.insert(0, stack.pop());
strBuffer.insert(0, "/");
}

return strBuffer.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Simplify Path