码迷,mamicode.com
首页 > 其他好文 > 详细

Simplify Path

时间:2015-08-18 17:59:12      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

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

Simplify Path

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4739543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!