Leetcode#71 Simplify Path

原题地址

 

用栈保存化简后的路径。把原始路径根据"/"切分成若干小段,然后依次遍历

若当前小段是"..",弹栈

若当前小段是".",什么也不做

否则,入栈

 

代码:

 1 string simplifyPath(string path) {
 2   vector<string> buffer;
 3   char *tok = NULL;
 4 
 5   tok = strtok((char *) path.c_str(), "/");
 6   while (tok) {
 7     cout << tok << endl;
 8     if (strcmp(tok, "..") == 0) {
 9       if (!buffer.empty())
10         buffer.pop_back();
11     }
12     else if (strcmp(tok, ".") != 0)
13       buffer.push_back(string(tok));
14     tok = strtok(NULL, "/");
15   }
16 
17   string res;
18   for (auto dir : buffer)
19     res += "/" + dir;
20   return buffer.empty() ? "/" : res;
21 }

 

posted @ 2015-01-25 16:31  李舜阳  阅读(153)  评论(0编辑  收藏  举报