第一版
class Solution {
public:
string simplifyPath(string path) {
vector<string> mysk;
string ret;
int i = 0;
int len = path.size();
while(i < len){
int count = 0;
int alpha = 0;
string word;
while(i < len && path[i] == '.'){
count++;
i++;
}
if(count == 2){
if(!mysk.empty())
mysk.pop_back();
}else if(count > 2){
mysk.push_back(string(count,'.'));
}
while(isalpha(path[i]) || path[i] == '_'){
alpha++;
i++;
}
word = path.substr(i-alpha,alpha);
if(!word.empty())
mysk.push_back(word);
i++;
}
if(mysk.empty()){
return "/";
}
for(i = 0;i < mysk.size();i++){
ret += ("/" +mysk[i]);
}
return ret;
}
};
第二版
class Solution {
public:
string simplifyPath(string path) {
vector<string> mysk;
string ret;
int i = 0;
int len = path.size();
while(i < len){
int count = 0;
int alpha = 0;
string word;
while(i < len && path[i] == '.'){
count++;
i++;
}
if(count == 2 && (i == len || path[i] == '/')&& i > 2 && path[i-3] == '/'){
if(!mysk.empty())
mysk.pop_back();
}else if(count > 2 && path[i] == '/'){
mysk.push_back(string(count,'.'));
}else if(count == 1 && (i == len || path[i] == '/')){
}else {
word += string(count,'.');
}
while(isalpha(path[i]) || path[i] == '_'){
alpha++;
i++;
}
word += path.substr(i-alpha,alpha);
if(!word.empty())
mysk.push_back(word);
i++;
}
if(mysk.empty()){
return "/";
}
for(i = 0;i < mysk.size();i++){
ret += ("/" +mysk[i]);
}
return ret;
}
};
第三版
class Solution {
public:
string simplifyPath(string path) {
vector<string> mysk;
string ret;
while(!path.empty()){
string word;
int cur = path.find('/');
if(cur == string::npos){
word = path;
}
word = path.substr(0,cur);
if(word == "."){
word = "";
// }else if(word == ".." && !mysk.empty()){
}else if(word == ".."){
if(!mysk.empty())
mysk.pop_back();
word = "";
}else if(!word.empty()){
mysk.push_back(word);
}
path.erase(0,cur+1);
if(cur == string::npos)
break;
}
if(mysk.empty()){
return "/";
}
for(int i = 0;i < mysk.size();i++){
ret += ('/' + mysk[i]);
}
return ret;
}
};
2022-7-19的一版
class Solution {
public:
string simplifyPath(string path) {
deque<string> m_stack;
int i = 0;
int len = path.size();
for (; i < len; i++){
while (i < len && path[i] == '/') i++;
int j = i;
while (j < len && path[j] != '/') j++;
string str = path.substr(i, j - i);
if (str == ".."){
if (!m_stack.empty())
m_stack.pop_back();
} else if (str != "" && str != "."){
m_stack.push_back(str);
}
i = j;
}
string ans;
while (!m_stack.empty()){
ans += '/';
string str = m_stack.front();
m_stack.pop_front();
ans += str;
}
return ans == "" ? "/" : ans;
}
};