*[Lintcode]Simplify Path简化路径
2016-11-13 11:12
176 查看
Given an absolute path for a file (Unix-style), simplify it.
Example
分析:用stack,先将路径split,得到的数组有几种字符需要处理 ".":代表当前目录,忽略 "../":代表上一级目录,出栈, 其他:代表路径名称,入栈
最后拼接成新路径。注意split在匹配时会出现空字符串匹配。
public class Solution {
/**
* @param path the original path
* @return the simplified path
*/
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] str = path.split("/");
//考虑/...
for(int i = 0; i < str.length; i++) {
if(str[i].equals(".")){
} else if(str[i].equals("..")) {
stack.pop();
} else {
stack.add(str[i]);
}
}
if(stack.isEmpty()) return "/";
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
if(stack.peek().equals("")) stack.pop();
else sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
Example
"/home/", =>
"/home"
"/a/./b/../../c/", =>
"/c"
分析:用stack,先将路径split,得到的数组有几种字符需要处理 ".":代表当前目录,忽略 "../":代表上一级目录,出栈, 其他:代表路径名称,入栈
最后拼接成新路径。注意split在匹配时会出现空字符串匹配。
public class Solution {
/**
* @param path the original path
* @return the simplified path
*/
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] str = path.split("/");
//考虑/...
for(int i = 0; i < str.length; i++) {
if(str[i].equals(".")){
} else if(str[i].equals("..")) {
stack.pop();
} else {
stack.add(str[i]);
}
}
if(stack.isEmpty()) return "/";
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
if(stack.peek().equals("")) stack.pop();
else sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
相关文章推荐
- [LintCode] Simplify Path 简化路径
- Leet Code 71 Simplify Path - 简化路径 - Java
- LeetCode-Simplify Path-路径简化-栈的应用
- 【Leetcode】71 Simplify path 简化路径
- LintCode-简化路径
- lintcode 中等题:Simplify Path 简化路径
- 简化路径-LintCode
- [LeetCode] Simplify Path,文件路径简化,用栈来做
- LeetCode OJ 之 Simplify Path (简化路径)
- Simplify Path 简化文件路径@LeetCode
- lintcode-简化路径-421
- [C++]LeetCode: 117 Simplify Path (简化Unix路径 list双向链表)
- [Leetcode] Simplify path 简化路径
- [LeetCode]—Simplify Path 简化路径表达式
- [LeetCode] Simplify Path 简化路径
- 使用类路径容器简化 Eclipse 类路径
- LintCode :不同的路径
- LintCode 二叉树中的最大路径和
- 返回给定绝对路径的,简化绝对路径
- lintcode(94)二叉树中的最大路径和