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

Commit03c47d6

Browse files
Add files via upload
1 parent03733eb commit03c47d6

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

‎simplify_path.cpp‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include<iostream>
2+
#include<string>
3+
#include<sstream>
4+
#include<vector>
5+
usingnamespacestd;
6+
7+
stringsimplifyPath(string path){
8+
//1. Step - Tokenisation & Filtering
9+
10+
istringstreamiss(path);
11+
vector<string> tokens;
12+
13+
string token;
14+
while(getline(iss,token,'/')){
15+
if(token=="."or token==""){
16+
continue;
17+
}
18+
tokens.push_back(token);
19+
}
20+
21+
22+
// 2. Handle ..
23+
vector<string> stack;
24+
25+
if(path[0]=='/'){
26+
//denotes that our path is an abs path (wrt root dir)
27+
stack.push_back("");
28+
}
29+
30+
for(string token : tokens){
31+
if(token==".."){
32+
//2 cases -> Abs path or relative path
33+
if(stack.size()==0or stack[stack.size()-1]==".."){
34+
stack.push_back("..");
35+
}
36+
37+
elseif(stack[stack.size()-1]!=""){
38+
stack.pop_back();
39+
}
40+
}
41+
else{
42+
//x,y,z...
43+
stack.push_back(token);
44+
}
45+
46+
}
47+
//single element
48+
if(stack.size()==1and stack[0]==""){
49+
return"/";
50+
}
51+
52+
//combine all elements in stack to get the answer
53+
ostringstream oss;
54+
int i =0;
55+
56+
for(auto token :stack){
57+
if(i!=0){
58+
oss<<"/";
59+
}
60+
i++;
61+
oss << token;
62+
}
63+
64+
return oss.str();
65+
66+
}
67+
68+
69+
intmain(){
70+
string path ="/../x/y/../z/././w/a///../../c/./";
71+
// Output : /x/z/c
72+
cout <<simplifyPath(path) <<endl;
73+
74+
75+
76+
return0;
77+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp