leetcode 100: Simplify Path
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(); } }