LeetCode 71. Simplify Path

一 题目

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shorteststring representing the absolute path.

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

Input: "/a//bc/d//././/.."
Output: "/a/b/c"

Accepted 167,020 Submissions 559,760

二 分析

medium 级别,题目要求把Unix操作系统的绝对路径变成简化路径。个人觉得有点实际意义,起码熟悉下路径,看脚本都好一些。

背景知识:熟悉的可以略过,“.” 当前层级,可以略过,“..”调到上一级。

路径都是“/”开头的。按要求简洁结束的“/”去掉。

回退的首先想到使用stack.利用出栈模拟“..”跳的上一级。

最后一点是输出结果的时候,注意下,栈是逆序输出的。

public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println( simplifyPath("/home/"));
		System.out.println( simplifyPath("/../"));
		System.out.println( simplifyPath("/home//foo/"));
		System.out.println( simplifyPath("/a/./b/../../c/"));
		System.out.println( simplifyPath("/a/../../b/../c//.//"));
		System.out.println( simplifyPath("/a//bc/d//././/.."));
	}
	
	/**
	 * @author bohu83
	 * @param path
	 * @return
	 */
	public static String simplifyPath(String path) {
		
		String[] strs= path.split("/");
		Stack s = new Stack();
		for(int i=0;i

Runtime: 5 ms, faster than 65.62% of Java online submissions for Simplify Path.

Memory Usage: 36.9 MB, less than 100.00% of Java online submissions forSimplify Path.

时间复杂度O(N)

总的来说,相对容易些.不想别的medium那么难。要想再快就得看看怎么优化下。

你可能感兴趣的:(leetcode,stack,simplify,Path,leetcode,String)