leetcode面试准备:Simplify Path

leetcode面试准备:Simplify Path

1 题目

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

接口:public String simplifyPath(String path)

2 思路

简化linux路径,主要对".." 进行回退操作。直观的想到用栈,在java里,栈用Deque的实现类LinkedList来做。

  1. path进行split
  2. stack中添加路径,进栈,出栈
  3. 最后将stack中元素输出

3 代码

    public String simplifyPath(String path) {
		String[] words = path.split("/");
		List<String> stack = new LinkedList<String>();
		for (String s : words) {
			if (s.equalsIgnoreCase("..")) {
				if (!stack.isEmpty())
					stack.remove(stack.size() - 1);
			} else if (!(s.length() == 0 || s.equalsIgnoreCase("."))) {
				stack.add(s);
			}
		}
		String res = "";
		for (String s : stack) {
			res += "/" + s;
		}
		return res.length() == 0 ? "/" : res;
	}

4 总结

栈的思想解决。

原文地址:https://www.cnblogs.com/byrhuangqiang/p/4801172.html