leetcode 100: Simplify Path
来源:互联网 发布:java独立开发 编辑:程序博客网 时间:2024/04/24 07:07
Simplify PathApr 4 '12
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
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"
.
HAPPY 100. my goal 300~
public class Solution { public String simplifyPath(String path) { // Start typing your Java solution below // DO NOT write main() function //path = "/a/./b/../../c/", => "/c" if(path==null) return null; String[] strs = path.split("/"); Stack<String> stack = new Stack<String>(); for( int i=0; i<strs.length; i++) { String s = strs[i]; if( s.equals(".") || s.length()==0) {//!alert: s.length==0 or u will have many ////. continue; } else if(s.equals("..") ) { if(!stack.isEmpty()){ stack.pop(); } } else { stack.push(s); } } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()) { sb.insert(0, stack.pop() ); sb.insert(0, "/"); } if(sb.length()==0) sb.insert(0, "/"); return sb.toString(); }}
public class Solution { public String simplifyPath(String path) { // Start typing your Java solution below // DO NOT write main() function //path = "/a/./b/../../c/", => "/c" if(path==null) return null; String[] strs = path.split("/"); Stack<String> stack = new Stack<String>(); for( int i=0; i<strs.length; i++) { String s = strs[i]; if( s.equals(".") || s.length()==0) {//!alert: s.length==0 or u will have many ////. continue; } else if(s.equals("..") ) { if(!stack.isEmpty()){ stack.pop(); } } else { stack.push(s); } } StringBuilder sb = new StringBuilder(); if(stack.isEmpty()) return "/"; Deque<String> alt = new ArrayDeque<String>(); while(!stack.isEmpty()) { alt.push( stack.pop() ); } while(!alt.isEmpty()) { sb.append("/" + alt.pop()); } return sb.toString(); }}
- leetcode 100: Simplify Path
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- [LeetCode] Simplify Path
- leetcode simplify path
- Leetcode: Simplify Path
- LeetCode题解:Simplify Path
- [LeetCode] Simplify Path
- LeetCode Simplify Path
- 添加交叉编译工具进入系统的环境变量
- java gc
- 算法--顺序统计-期望线性时间做选择
- gcc编译静态库和动态库
- Android一句话区分sendBroadcast与sendStickyBroadcast
- leetcode 100: Simplify Path
- Fatal error: Class 'ZipArchive' not found的解决办法
- android屏幕自适应
- SSH框架与SSI框架的区别
- javascript的变量
- XNA游戏绘图
- 打开网页输入用户名和密码时,字体非常小,只显示————————
- Nginx http_core模块 配置文件解析
- maximo开发经验