码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode# 71 Simplify Path

时间:2015-01-25 18:09:35      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

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

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

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

否则,入栈

 

代码:

 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 }

 

Leetcode# 71 Simplify Path

标签:

原文地址:http://www.cnblogs.com/boring09/p/4248403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!