要求:
给定一个UNIX风格的全路径,简化它,例如:
“/home/” => “/home”
“/a/./b/../../c/” => “/c”
做法:
1.
“."指的是当前目录,”..“指的是上级目录,"cd / ” 则是返回根目录;
2.
初始化一个vector1,我们将这个全路径按 “/” 分割,存储在vector1里;
3.
然后初始化另一个vector2,遍历这个vector1,遇到文件夹,则将它添加到vector2的尾部,遇到 “..” 则删除vector2的尾部的元素,如遇到 “” 或 “ . ” 则跳过继续遍历,根据这个特点,也可以用栈来实现;
4.
最后将vector2输出,拼接字符串;
代码实现:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void spilt(const char* str,const char* deli,vector<string>* ve,int n){
char tmp[n+1];
snprintf(tmp, sizeof(tmp), str);
ve->clear();
char* gg;
char* p = strtok_r(tmp, deli, &gg);
while (p!=NULL) {
ve->push_back(p);
p = strtok_r(NULL, deli, &gg);
}
}
string simplifyPath(string path) {
vector<string> ve;
vector<string> newVe;
//字符串转化为char*
const char* str = path.c_str();
spilt(str, "/", &ve,(int)path.length());
int n = (int)ve.size();
for (int i = 0; i<n; i++) {
if (ve[i]==""||ve[i]==".") {
continue;
}else{
if (ve[i]=="..") {
if (!newVe.empty()) {
newVe.pop_back();
}
}else{
newVe.push_back(ve[i]);
}
}
}
if (newVe.empty()) {
return "/";
}else{
int m = (int)newVe.size();
string newStr = "";
for (int i=0; i<m; i++) {
newStr = newStr+"/"+newVe[i];
}
return newStr;
}
}
};
int main(int argc, const char * argv[]) {
Solution* s = new Solution();
cout<<s->simplifyPath("///HSGambA/..///DLCkPZxIAWDX/iIQIncFWSaMLG/././RVOlTgYl/NnTHKiAVWVCPCARqna///lxbPdAlgTC/eXBfVOBuPbBRb/////iy///../gE/MoNMalkJgUChQbXuRogz/./../FkR/././././GtP///./..///CAiQtMuRub/xOcs/RtEkqhqCLZAkCzdX/////SNMEIs/cyneqrDxUosUhcGAB/bPHrLgioq/./HhFgLUjEFrg/nKlbXBRicXjxNBLD/.///.///LIUAUsBU/kTqEWZYpIdRRxDV/////pLjoiqd/mMgSebGPyZ/./VQAErxTVbJtFGJ/wyeOwQUEwz/../.././//d/../../qmYZmdXO///liGrmA/.././../Cc///tOLsCMtVJcDDKcuPM///./fywuWZOHnln/UjepoOdc/CVSRAwOielKl/../ExXI/SYsxkdfeRHPuRZhsRrQc/./RxruFyUPeisM/../uyGh/EjJsGlCLKMpnzS/SYoyFtsznGK/./mnbKK/../SLAKsHcouXPKSQwJa/./../NPn/kHeVSrDVVfhv/P/../CSXZeqLgJOLbyZZNiJGa/L///AOldPsSFIZqKKixZQ/evwGyGJhoKvvyot/pWtiAkFrvnLTbZZT/EkKrRJyXmNoUWCDr/qHgRjqETRtMfrX/WZxvvGRWclANrbuLuu///xBOFLDmoQtYQhjK/../MCRZBSWX/IYshVeeYGeHEPAsDYDp///pNnHlXfOQCVJu/../Ux/../HFaPOmbhjNq/OXRFgVU/uxMsClzPA/./cPlqKKvZNAQKzwFL///uvKKsZoHjZArQQ/DJruUeMYHMlhKPkFMy/NqdCweXujNHGJTL/tjhFFsOMeXWlNeDJjf/EeWUzIHmqfS/.././DDmiy///.././EqjhEiYgVbHo/NTvBQ/././//../nMzJgmVGcMlZgTQhwC/.///MXtPzGrZEB/WynGrD/////../PidAvghpCyxRYQRKaZEF/../mtoy//")<<endl;
return 0;
}
|