Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit d514441

Browse filesBrowse files
author
applewjg
committed
SimplifyPath
Change-Id: I2cefaca9f3b954bf64b5a3262c4b52c8b8039f32
1 parent a5e77a5 commit d514441
Copy full SHA for d514441

File tree

Expand file treeCollapse file tree

1 file changed

+46
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+46
-0
lines changed
Open diff view settings
Collapse file

‎SimplifyPath.java‎

Copy file name to clipboard
+46Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 11, 2015
4+
Problem: Simplify Path
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/simplify-path/
7+
Notes:
8+
Given an absolute path for a file (Unix-style), simplify it.
9+
10+
For example,
11+
path = "/home/", => "/home"
12+
path = "/a/./b/../../c/", => "/c"
13+
14+
Corner Cases:
15+
Did you consider the case where path = "/../"?
16+
In this case, you should return "/".
17+
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
18+
In this case, you should ignore redundant slashes and return "/home/foo".
19+
20+
Solution: Add an additional '/' at the end of 'path' for simply detecting the end.
21+
*/
22+
public class Solution {
23+
public String simplifyPath(String path) {
24+
if(path.length()==0) return "/";
25+
if(path.charAt(0)!='/') return "/";
26+
ArrayList<String> dirs = new ArrayList<String>();
27+
String[] str = path.split("/");
28+
for (int i = 0; i < str.length; ++i) {
29+
if ((i == 0 || i == str.length - 1) && str[i].compareTo("") == 0) continue;
30+
if (str[i].compareTo("..") == 0) {
31+
if (dirs.isEmpty() == false) {
32+
dirs.remove(dirs.size() - 1);
33+
}
34+
} else if ((str[i].compareTo(".") != 0) && (str[i].compareTo("") != 0)) {
35+
dirs.add(str[i]);
36+
}
37+
}
38+
if (dirs.isEmpty() == true) return "/";
39+
StringBuilder res = new StringBuilder();
40+
for (int i = 0; i < dirs.size(); ++i) {
41+
res.append("/");
42+
res.append(dirs.get(i));
43+
}
44+
return res.toString();
45+
}
46+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.