zoukankan      html  css  js  c++  java
  • leetcode面试准备:Simplify Path

    leetcode面试准备:Simplify Path

    1 题目

    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".

    接口:public String simplifyPath(String path)

    2 思路

    简化linux路径,主要对".." 进行回退操作。直观的想到用栈,在java里,栈用Deque的实现类LinkedList来做。

    1. path进行split
    2. stack中添加路径,进栈,出栈
    3. 最后将stack中元素输出

    3 代码

        public String simplifyPath(String path) {
    		String[] words = path.split("/");
    		List<String> stack = new LinkedList<String>();
    		for (String s : words) {
    			if (s.equalsIgnoreCase("..")) {
    				if (!stack.isEmpty())
    					stack.remove(stack.size() - 1);
    			} else if (!(s.length() == 0 || s.equalsIgnoreCase("."))) {
    				stack.add(s);
    			}
    		}
    		String res = "";
    		for (String s : stack) {
    			res += "/" + s;
    		}
    		return res.length() == 0 ? "/" : res;
    	}
    
    

    4 总结

    栈的思想解决。

  • 相关阅读:
    keyCode对照表
    WebApi的前端调用
    AJAX get和post请求
    Linq中常用语法
    MVC三种分页方法
    常用DBhelper封装方法
    ASP.NET MVC 导入Excel文件(完整版)
    Razor语法2
    MVC之路由规则 (自定义,约束,debug)
    MVC
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4801172.html
Copyright © 2011-2022 走看看