Simplify Path
Simplify Path
问题:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
思路:
典型栈的问题
我的代码:
public class Solution { public String simplifyPath(String path) { if(path == null || path.length() == 0) return ""; String[] paths = path.split("/"); Stack<String> stack = new Stack<String>(); for(String str: paths) { if(str.equals("")) continue; if(str.equals(".")) {} else if(str.equals("..")) { if(!stack.isEmpty()) stack.pop(); } else stack.push(str); } String rst = new String(); while(!stack.isEmpty()) { rst = "/"+ stack.pop() + rst; } if(rst.equals("")) return "/"; return rst; } }
posted on 2015-03-31 21:06 zhouzhou0615 阅读(142) 评论(0) 编辑 收藏 举报