总结
1. 做这种题时需要考虑 corner case, 比如连续几个 slash
2. 状态函数带参数 (int &pos), 主函数带 while 循环 while(pos < len), 我意识到对于 char* 或 string 操作时, 参数带上 lenth 也是蛮好的
3. 这次很快就 A 了, 甚至忘记以前为什么会在这里栽跟头
代码
string getFolderName(const string &path, int &i, const int &len) { string res; while(i < len && path[i] != '/') { res.push_back(path[i]); i ++; } return res;}class Solution {public: string simplifyPath(string path) { dequerecord; int i = 0; int len = path.size(); while(i < len) { if(path[i] == '/') { i ++; } else { string folderName = getFolderName(path, i, len); if(folderName == ".") { // do nothing } else if(folderName.size() == 2 && folderName == "..") { if(!record.empty()) record.pop_back(); } else { record.push_back(folderName); } } } string simplifiedPath = ""; while(!record.empty()) { simplifiedPath.push_back('/'); simplifiedPath.append(record.front()); record.pop_front(); } if(simplifiedPath.size() == 0) { simplifiedPath = "/"; } return simplifiedPath; }};