[Leetcode] Simplify Path

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

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

 

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

 

 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 };

 

posted @ 2014-03-28 14:18  Eason Liu  阅读(529)  评论(0编辑  收藏  举报