首页 > 其他 > 详细

[Leetcode] Simplify Path

时间:2014-03-28 23:51:42      阅读:717      评论:0      收藏:0      [点我收藏+]

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

 

用栈实现即可,注意一些特殊情况的判断。

 

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         stack<string> s;
 5         string str;
 6         int a, b;
 7         bool flag = true;
 8         for (int i = 0; i < path.length(); ++i) {
 9             if (path[i] == /) {
10               path[i] =  ;
11             }
12         }
13         istringstream sin(path);
14         while (sin >> str) {
15             if (str == ".." && !s.empty()) {
16                 s.pop();
17             } else if (str == "." || str == ".." && s.empty()) {
18                 
19             } else {
20                 s.push(str);
21             }
22         }
23         string res = "";
24         if (s.empty()) {
25             return "/";
26         }
27         while (!s.empty()) {
28             res = "/" + s.top() + res;
29             s.pop();
30         }
31         return res;
32     }
33 };
bubuko.com,布布扣

[Leetcode] Simplify Path,布布扣,bubuko.com

[Leetcode] Simplify Path

原文:http://www.cnblogs.com/easonliu/p/3630580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!