71. Simplify Path

网友投稿 257 2022-12-01

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example, path = “/home/”, => “/home” path = “/a/./b/…/…/c/”, => “/c” click to show corner cases.

思路: 首先将所有的内容从/中分离出来,然后分别处理。这里我们需要用到堆栈的数据结构。堆栈有很多种实现方式,java中的Stack类LinkedList类都可以实现其功能。我们将读到的路径入栈,根据操作符出栈,最后将栈中剩余的元素组织成String路径返回即可。

class Solution { public String simplifyPath(String path) { Stack s = new Stack(); String[] pathDetail = path.split("/"); for(int i = 0 ; i < pathDetail.length ; i++){ //弹出上级目录,如果有上级目录 if (pathDetail[i].equals("..")){ if (s.isEmpty()){ continue; } s.pop(); //不进行任何操作 } else if (pathDetail[i].equals(".") || pathDetail[i].isEmpty()){ continue; } else { s.push(pathDetail[i]); } } if (s.isEmpty()){ return "/"; } StringBuilder result = new StringBuilder(); do { result.insert(0, s.pop()); result.insert(0, "/"); } while (!s.isEmpty()); return result.toString(); }}

class Solution { public String simplifyPath(String path) { if(path == null || path.length() < 1) return path; Deque deque = new LinkedList(); int index = 0; StringBuilder ans = new StringBuilder(); while(index < path.length()) { if(path.charAt(index) != '/') { StringBuilder dirName = new StringBuilder(); int dots = 0; while(index < path.length() && path.charAt(index) != '/') { dirName.append(path.charAt(index) + ""); if(path.charAt(index++) == '.') { dots++; } else dots = 0; } if(dirName.length() > 2 || dots == 0) deque.add(dirName.toString()); else if(dots == 2) if(!deque.isEmpty()) deque.removeLast(); } while(index < path.length() && path.charAt(index) == '/') index++; } if(deque.isEmpty()) return "/"; while(!deque.isEmpty()) ans.append("/" + deque.removeFirst()); return ans.toString(); }}

class Solution: def simplifyPath(self, path: str) -> str: lst = path.split('/') stack = [] for x in lst: if x in ['.','']: continue if x == '..': if stack: stack.pop() else: stack.append(x) return '/' + '/'.join(stack)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:206. Reverse Linked List
下一篇:654. Maximum Binary Tree
相关文章

 发表评论

暂时没有评论,来抢沙发吧~