Simplify Path
问题描述
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".
解决思路
双端队列(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
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号