Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Commitd514441

Browse files
author
applewjg
committed
SimplifyPath
Change-Id: I2cefaca9f3b954bf64b5a3262c4b52c8b8039f32
1 parenta5e77a5 commitd514441

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎SimplifyPath.java

Lines 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+
publicclassSolution {
23+
publicStringsimplifyPath(Stringpath) {
24+
if(path.length()==0)return"/";
25+
if(path.charAt(0)!='/')return"/";
26+
ArrayList<String>dirs =newArrayList<String>();
27+
String[]str =path.split("/");
28+
for (inti =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+
}elseif ((str[i].compareTo(".") !=0) && (str[i].compareTo("") !=0)) {
35+
dirs.add(str[i]);
36+
}
37+
}
38+
if (dirs.isEmpty() ==true)return"/";
39+
StringBuilderres =newStringBuilder();
40+
for (inti =0;i <dirs.size(); ++i) {
41+
res.append("/");
42+
res.append(dirs.get(i));
43+
}
44+
returnres.toString();
45+
}
46+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp