Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.Stack;
public class SimplifyPath {
public String simplifyPath(String path) {
if(path == null) return null;
Stack<String> s = new Stack<String>();
int len = path.length();
StringBuilder b = new StringBuilder();
String item = null;
for (int i = 1; i < len; i++){ // start with the char at index 1 since the first is always '/'
char c = path.charAt(i);
if (c != '/'){
b.append(c);
}
if(c == '/' || i == len - 1){
item = b.toString();
b = new StringBuilder(); // must empty the StringBuilder!
if (item.equals("") || item.equals(".")) continue;
else if (item.equals("..")){
if(s.size() > 0) s.pop();
else continue;
}else{
s.push(item);
}
}
}
if(s.isEmpty()) return "/";
String[] temp = new String[s.size()];
int i = temp.length - 1;
while(s.isEmpty() != true){
temp[i] = s.pop();
i--;
}
StringBuilder pathB = new StringBuilder();
for (i = 0; i < temp.length; i++){
pathB.append("/");
pathB.append(temp[i]);
}
return pathB.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment