awsl
测试用例"/…" 不过 自己也不知道如何去改了😭
参考liuyubobobo老师的代码(真优雅👀)
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack; //这里并没有真正用栈,不然倒来倒去有点麻烦
for(int start = 1, i = 1; i <= path.size(); i ++)
if(i == path.size() || path[i] == '/'){
string f = path.substr(start, i - start);
if(f.size()){
if(f == ".."){
if(stack.size()) stack.pop_back();
}
else if(f != ".") stack.push_back(f); //为字母的情况
//为.的情况就直接不放入最终的vector中了
}
start = i + 1;
}
string res = ""; //解决了 "/..."这个测试用例的问题 当后面都没有/的时候
for(string e: stack)
res += "/" + e;
return res == "" ? "/" : res; //处理栈为空时的情况
}
};
我遇到过的问题
"/../" 还有 "/c//" 矛盾了
这里是自己当栈为空的时候没返回好
"/." "/..." 也错了
这里是末尾的.
没有判断好
末尾的. / 都要特殊判断一下
我的一坨代码。。。😭
class Solution {
public:
string simplifyPath(string path) {
stack<char> symbol;
if(path[0] != '/')
return "";
else
symbol.push(path[0]);
for(int i = 1 ; i < path.size(); i++ ){
if(path[i] != '/' & path[i] != '.')
symbol.push(path[i]);
else if(path[i] == '/'){
char match = symbol.top();
if( i != path.size()-1 & match == '/') continue; //因为最后要处理一下栈顶的/ 所以这里要加一个判断
else{
if(match == '.'){
symbol.pop();
}else
symbol.push(path[i]);
}
}else if(path[i] == '.'){
char match = symbol.top();
if(match != '.' && i != path.size()-1 ) symbol.push(path[i]);
else if(match != '.' && i == path.size()-1) continue;
else{
if(symbol.size() == 2) symbol.pop();
else{
symbol.pop(); //点
symbol.pop(); //杠
symbol.pop(); //字母
}
}
}
}
stack<char> result;
while(symbol.size() != 1 && symbol.top() == '/' ) symbol.pop();
while(!symbol.empty()){
result.push(symbol.top());
symbol.pop();
}
string res;
int n = result.size();
for(int i = 0 ; i < n; i++){
res += result.top();
result.pop();
}
return res;
}
};