文章目录
  1. 1. Simplify Path
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Simplify Path

题目

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = “/home/“, => “/home”

path = “/a/./b/../../c/“, => “/c”

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”.

思路

建立一个字符串栈,/后面的字符们(直到/为止)作为一个字符串,若字符串为..,若栈不为空,则栈顶元素出栈。若字符串不为”.”或者””,则将字符串入栈。

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
string simplifyPath(string path) {
stack<string> ss;
for(int i=0;i<path.size();){
while(i<path.size() && '/'==path[i])
++i;
string s="";
while(i<path.size() && path[i]!='/')
s+=path[i++];
if(".."==s && !ss.empty())
ss.pop();
else if(s!="" && s!="." && s!="..")
ss.push(s);
}
if(ss.empty())
return "/";
string s="";
while(!ss.empty()){
s="/"+ss.top()+s;
ss.pop();
}
return s;
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# @param {string} path
# @return {string}
def simplifyPath(self, path):
ss=[]
i=0
while i<len(path):
while i<len(path) and '/'==path[i]:
i=i+1
s=""
while i<len(path) and path[i]!='/':
s+=path[i]
i=i+1
if(".."==s and len(ss)!=0):
ss.pop()
elif (s!="" and s!="." and s!=".."):
ss.append(s)
if(len(ss)==0):
return "/"
s=""
while(len(ss)!=0):
s="/"+ss[-1]+s
ss.pop()
return s

文章目录
  1. 1. Simplify Path
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题