您的位置:首页 > 其它

*[Lintcode]Simplify Path简化路径

2016-11-13 11:12 176 查看
Given an absolute path for a file (Unix-style), simplify it.

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