zoukankan      html  css  js  c++  java
  • 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.

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

    解决思路

    双端队列(LinkedList).

    程序

    public class Solution {
        public String simplifyPath(String path) {
    		if (path == null || path.trim().length() == 0) {
    			return "";
    		}
    		
    		String[] splits = path.split("/");
    		LinkedList<String> ll = new LinkedList<String>();
    		
    		for (int i = 0; i < splits.length; i++) {
    			String spl = splits[i];
    			if (spl.trim().length() == 0) {
    				continue;
    			}
    			if (spl.equals(".")) {
    				continue;
    			}
    			if (spl.equals("..")) {
    				if (!ll.isEmpty()) {
    					ll.removeLast();
    				}
    				continue;
    			}
    			ll.add(spl.trim());
    		}
    		
    		if (ll.isEmpty()) {
    			return "/";
    		}
    		
    		StringBuilder sb = new StringBuilder();
    		while (!ll.isEmpty()) {
    			sb.append("/" + ll.removeFirst());
    		}
    		
    		return sb.toString();
    	}
    }
    

    附上测试用例

    String[] paths = { "/home/", "/a/./b/../../c/", "/../", "/home//foo/",
    				"/home/foo/.ssh/../.ssh2/authorized_keys/" };
    

    Output

    path:/home/ | /home
    path:/a/./b/../../c/ | /c
    path:/../ | /
    path:/home//foo/ | /home/foo
    path:/home/foo/.ssh/../.ssh2/authorized_keys/ | /home/foo/.ssh2/authorized_keys

  • 相关阅读:
    vue-cli生成的重要代码详解
    vuex初探
    vue-router笔记
    新技术的学习
    图片优化方法(有时间看看)
    关于老教授之家项目的思考 && 中国互联网+大赛培训
    If you are tired...
    微信公众平台开发初探
    winscp介绍与使用
    获取当前服务器信息
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4739543.html
Copyright © 2011-2022 走看看