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 总结

    栈的思想解决。

  • 相关阅读:
    【洛谷4251】 [SCOI2015]小凸玩矩阵(二分答案,二分图匹配)
    JXOI2019游记
    luogu4884 多少个1?
    数论难点选讲
    计树问题小结
    codeforces选做1.0
    POI2015选做
    后缀自动机小结
    bzoj4008 [HNOI2015]亚瑟王
    bzoj1500 [NOI2005]维修数列
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4801172.html
Copyright © 2011-2022 走看看