Skip to content

Commit

Permalink
Simplify Path
Browse files Browse the repository at this point in the history
  • Loading branch information
mengli committed Jan 6, 2014
1 parent 3518e16 commit 3cd8c92
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions SimplifyPath.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.LinkedList;
import java.util.List;

/**
* Given an absolute path for a file (Unix-style), simplify it.
*
* For example,
*
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
*
* click to show corner cases.
*
* 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 class SimplifyPath {
public String simplifyPath(String path) {
int length = path.length();
if (length == 0)
return path;
List<String> dicts = new LinkedList<String>();
int slow = 0;
int fast = 0;
while (true) {
while (slow < length && path.charAt(slow) == '/') {
slow++;
}
if (slow >= length)
break;
fast = slow;
while (fast < length && path.charAt(fast) != '/') {
fast++;
}
String s = path.substring(slow, fast);
if (s.equals("..")) {
if (!dicts.isEmpty()) {
dicts.remove(dicts.size() - 1);
}
} else if (!s.equals(".")) {
dicts.add(s);
}
slow = fast;
}
StringBuffer ret = new StringBuffer();
for (String s : dicts) {
ret.append('/');
ret.append(s);
}
return ret.length() == 0 ? "/" : ret.toString();
}
}

0 comments on commit 3cd8c92

Please sign in to comment.