Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
使用一个栈来解决问题。遇到'..'弹栈,遇到'.'不操作,其他情况下压栈。
代码一:
class Solution: # @param path, a string # @return a string def simplifyPath(self, path): stack = [] i = 0 res = '' while i< len(path): end = i+1 while end<len(path) and path[end] !="/": end += 1 sub = path[i+1:end] if len(sub)>0: if sub == "..": if stack !=[]: stack.pop() elif sub != ".": stack.append(sub) i = end if stack == []: return "/" for i in stack: res += "/"+i return res
code 2:
class Solution: def simplifyPath(self,path): path = path.split('/') res = '/' for i in path: if i == '..': if res != '/': res = '/'.join(res.split('/')[:-1]) if res =='': res = '/' elif i != '.' and i != '': res += '/' +i if res != '/' else i return res
转自(参考):
1. http://www.cnblogs.com/zuoyuan/p/3777289.html
2. http://blog.csdn.net/linhuanmars/article/details/23972563
@ JAVA 版本
public String simplifyPath(String path) { if(path == null || path.length()==0) { return ""; } LinkedList<String> stack = new LinkedList<String>(); StringBuilder res = new StringBuilder(); int i=0; while(i<path.length()) { int index = i; StringBuilder temp = new StringBuilder(); while(i<path.length() && path.charAt(i)!='/') { temp.append(path.charAt(i)); i++; } if(index!=i) { String str = temp.toString(); if(str.equals("..")) { if(!stack.isEmpty()) stack.pop(); } else if(!str.equals(".")) { stack.push(str); } } i++; } if(!stack.isEmpty()) { String[] strs = stack.toArray(new String[stack.size()]); for(int j=strs.length-1;j>=0;j--) { res.append("/"+strs[j]); } } if(res.length()==0) return "/"; return res.toString(); }