链接:https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1013/
代码:
#include <stack> class Solution { public: string simplifyPath(string path) { int len = path.size(); int i = 0; stack<string> s; while(i < len) { while(i < len && path[i] == '/') { i++; } int flag1 = 0; int flag2 = 0; int flag3 = 0; if((i<len&&i+1<len&&i+2<len) && path[i]=='.' && path[i+1] == '.' && path[i+2] != '/') flag1 = 1; if((i<len&&i+1<len) && path[i] == '.' && path[i+1] != '/' && path[i+1] != '.') flag2 = 1; if(i < len && path[i] != '.') flag3 = 1; if(flag1 || flag2 || flag3) { cout << "flag123" << endl; // in stack string temp = ""; while(i < len && path[i] != '/') { temp += path[i]; i++; } s.push(temp); continue; } int flag4 = 0; if((i<len&&i+1<len) && path[i] == '.' && path[i+1] == '.') flag4 = 1; if(flag4) { cout << "flag4" << endl; // .. if valid, back to previous layer if(!s.empty()) { s.pop(); } i += 2; continue; } int flag5 = 0; if(i < len && path[i] == '.') flag5 = 1; if(flag5) { cout << "flag5" << endl; // . stay the same i++; continue; } } if(s.empty()) return "/"; stack<string> ans; while(!s.empty()) { ans.push(s.top()); s.pop(); } string res = ""; while(!ans.empty()) { res += "/"; res += ans.top(); ans.pop(); } return res; } };
思路:字符串切割,注意"..*" ".*" "../" "./"情况要好好讨论,不能先讨论前缀,再运用栈(主要是".."类似于弹栈操作)输出。