博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode#71]Simplify Path
阅读量:5218 次
发布时间:2019-06-14

本文共 2725 字,大约阅读时间需要 9 分钟。

Problem:

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

For example,

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Analysis:

This problem is very very easy, if you really understand how to read linux path. Big idea:Maintain a stack, then interpret the element between "/" one by one.iff the element is "..", we pop one element outiff the element is ".", we do nothing with it.iff the element is "directory/file name", we push it onto the stack.

Initial Wrong Solution:

public class Solution {    public String simplifyPath(String path) {        if (path == null)            throw new IllegalArgumentException("The passed in path is null!");        String[] stubs = path.split("/");        Stack
stack = new Stack
(); for (String stub : stubs) { if (stub.equals("..")) { if (!stack.isEmpty()) stack.pop(); } else if (!stub.equals(".")) { stack.push(stub); } } StringBuffer ret = new StringBuffer(); while (!stack.isEmpty()) { ret.insert(0, stack.pop()); ret.insert(0, "/"); } if (ret.charAt(0) != '/') ret.insert(0, "/"); return ret.toString(); }}

Mistakes Analysis:

Even though it is easy, I have made following mistakes in implementation.Mistake 1: ignore the case "/", which would result in "no element pushed onto the stack".Then tried following error fix:if (ret.charAt(0) != '/')    ret.insert(0, "/");This is absolutely wrong, since ret is empety, this would cause expcetion.Fix: if (ret.length() == 0)    return "/";Mistake 2: ignore the String.spilit could produce "" as element.Case: "/..."String.split => ["", "..."]Fix:for (String stub : stubs) {    if (stub.equals("..")) {    ...    }}

Solution:

public class Solution {    public String simplifyPath(String path) {        if (path == null)            throw new IllegalArgumentException("The passed in path is null!");        String[] stubs = path.split("/");        Stack
stack = new Stack
(); for (String stub : stubs) { if (stub.equals("")) continue; if (stub.equals("..")) { if (!stack.isEmpty()) stack.pop(); } else if (!stub.equals(".")) { stack.push(stub); } } StringBuffer ret = new StringBuffer(); while (!stack.isEmpty()) { ret.insert(0, stack.pop()); ret.insert(0, "/"); } if (ret.length() == 0) return "/"; return ret.toString(); }}

转载于:https://www.cnblogs.com/airwindow/p/4779850.html

你可能感兴趣的文章
SpringMvc服务端实现跨域请求解决方案
查看>>
ognl表达式
查看>>
安卓高手之路 图形系统(3 底层SurfceFlinger系统)
查看>>
Web 前端开发精华文章推荐(jQuery、HTML5、CSS3)【系列十三】
查看>>
LA 3135 优先队列
查看>>
JQuery EasyUI后台UI框架使用连载
查看>>
codeforce 5E(dp阵亡)
查看>>
【Android】Android 开机广播的使用
查看>>
将 Shiro 作为应用的权限基础 二:shiro 认证
查看>>
tomcat 虚拟目录的安全问题
查看>>
react 中echarts-for-react使用 自适应div
查看>>
lvM增减教程-转
查看>>
js基础之动画(二)
查看>>
The method of type must override a superclass method解决方式(转)
查看>>
bzoj 4506: [Usaco2016 Jan]Fort Moo
查看>>
leecode 旋转数组
查看>>
大型网站架构系列:缓存在分布式系统中的应用(一)
查看>>
$.proxy用法(解决this转移问题)
查看>>
ORA-28001
查看>>
工作笔记-关于面试
查看>>