https://leetcode.com/problems/simplify-path/#/description
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
package go.jacob.day723;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
/**
* 71. Simplify Path
*
* @author Jacob
* 有两种解法,第一种使用堆栈,第二种是我第一次做题的解法,可以作为参考
*
*/
public class Demo1 {
/*
* Java solution with stack
*/
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
Set<String> set = new HashSet<String>(Arrays.asList(".", "..", ""));
for (String s : path.split("/")) {
if (s.equals("..") && !stack.isEmpty())
stack.pop();
else if (!set.contains(s))
stack.push(s);
}
StringBuilder sb = new StringBuilder();
for (String s : stack) {
sb.append("/" + s);
}
/*
* 以下写法是错误的,因为堆栈是先进后出
* while(!stack.isEmpty()){
* sb.append("/"+stack.pop()); }
*/
return sb.length() == 0 ? "/" : sb.toString();
}
/*
*
* 这是我自己的解法
* My Solution.Runtime: 10 ms.Your runtime beats 75.56 % of java
* submissions.
*
*/
public String simplifyPath_1(String path) {
if (path == null || path.length() == 0)
return "/";
String[] dirs = path.split("/");
ArrayList<String> list = new ArrayList<String>();
for (String s : dirs) {
if (s.equals(".") || s.equals(""))
continue;
if (s.equals("..")) {
if (!list.isEmpty()) {
list.remove(list.size() - 1);
}
} else {
list.add("/" + s);
}
}
if (list.isEmpty())
return "/";
StringBuilder res = new StringBuilder();
for (String s : list) {
res.append(s);
}
return res.toString();
}
}