您的位置:首页 > 其它

[LeetCode]Simplify Path

2016-11-27 23:30 232 查看
https://leetcode.com/problems/simplify-path/

string.split的时候如果两个标志之间没有值也会返回一个空字符串,stack用ArrayDeque,“/..”和“/home//test”都是合法输入

public class Solution {
public String simplifyPath(String path) {
if (path == null) return path;
String[] arr = path.split("/");
Deque<String> stack = new ArrayDeque<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(".") || arr[i].length() == 0) continue;
else if (arr[i].equals("..")) {
if (!stack.isEmpty()) stack.pop();
}
else stack.push(arr[i]);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: