题目:biubiu
题意:根据题意处理一个字符串。
我使用的栈进行处理,后面的子串有可能对前面的子串产生影响,可以使用栈先进后出的特性。然后进行遍历处理相应的情况。
注意: 使用栈,当你面对其中一种情况需要判断前一个子串也就是栈头元素时,一定要考虑栈是否为空,对栈中元素进行一个预判,防止空栈进行元素操作。
代码:
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
stack<string>p;
string str;
p.push("/");
for (int i = 0; i < path.size(); i++) {
str.erase(0);
if (path[i] == '/') {
if (i == path.size() - 1)
continue;
str.append(1, path[i]);
if (p.size() == 0) {///注意
p.push(str);
continue;
}
if (p.top() == "/")
continue;
else
p.push(str);
}
else if (path[i] == '.') {
for (int j = i; j < path.size() && path[j] != '/'; j++) {
str.append(1, path[j]);
i = j;
}
if (str.size() == 1) {
continue;
}
else if (str.size() == 2) {
p.pop();
if (p.size()) {
p.pop();
}
}
else {
p.push(str);
}
}
else {
for (int j = i; j < path.size() && path[j] != '/'; j++) {
str.append(1, path[j]);
i = j;
}
p.push(str);
}
}
str.erase(0);
if (p.size() == 0) {
str = "/";
return str;
}
while (p.size()) {///注意
if (p.top() == "/")
p.pop();
else
break;
}
while (p.size()) {
str.insert(0, p.top());
p.pop();
}
if (str.size() == 0)
str.insert(0, 1, '/');
return str;
}
};
int main() {
string path;
while (cin >> path) {
Solution s;
cout << s.simplifyPath(path) << endl;
}
return 0;
}