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

  • 相关阅读:
    树的重心备忘
    Hdu 2196
    HDU 1520
    TOJ1068 商务旅行
    携程HDU第一场1001
    USACO 4.3.2 The Primes
    Html常用标签的应用
    Html
    开班心得
    for循环练习及字符串处理
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4739543.html
Copyright © 2011-2022 走看看