Skip to content

Commit dbbd4ac

Browse files
authored
Create simplify_path.md
1 parent 0407e4b commit dbbd4ac

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

simplify_path.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Simplify Path
2+
## Problem
3+
Given an absolute path for a file (Unix-style), simplify it.
4+
5+
For example,
6+
path = "/home/", => "/home"
7+
path = "/a/./b/../../c/", => "/c"
8+
9+
click to show corner cases.
10+
Corner Cases:
11+
12+
Did you consider the case where path = "/../"?
13+
In this case, you should return "/".
14+
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
15+
In this case, you should ignore redundant slashes and return "/home/foo".
16+
## 问题分析
17+
主要是对数组遍历分情况对数组inking处理,
18+
## 代码实现
19+
```C
20+
char* simplifyPath(char* path) {
21+
int i, t=1;//i用做数组下标,t用来计算返回路径的下标
22+
int len = strlen(path);
23+
path[0] = '/'; //返回的路径第一个都为'/'
24+
for(i=1; i<len; i++) {
25+
if(path[i]=='.' && ((i+1<len && path[i+1]=='/') || path[i+1]=='\0')) {
26+
i = i + 1;
27+
}
28+
else if(path[i]=='.' && i+1<len && path[i+1]=='.' && ((i+2<len && path[i+2]=='/') || path[i+2]=='\0')) {
29+
i = i + 2;
30+
t = t - 2 < 0? 0: t-2;
31+
while(path[t]!='/') {
32+
t--;
33+
}
34+
t++;
35+
}
36+
else if(path[i]=='/') {
37+
continue;
38+
}
39+
else {
40+
while(i<len && path[i]!='/'){
41+
path[t++] = path[i++];
42+
}
43+
path[t++] = path[i];
44+
}
45+
}
46+
if(t>1) {
47+
path[t-1] = '\0';
48+
}
49+
else {
50+
path[t] = '\0';
51+
}
52+
return path;
53+
}
54+
55+
```

0 commit comments

Comments
 (0)