Sunday, May 17, 2015

Simplify Path

来源:Leetcode

原帖:http://oj.leetcode.com/problems/simplify-path/

题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
Solution: Add an additional '/' at the end of 'path' for simply detecting the end.
/./ not change the path.

代码:
 class Solution {  
 public:  
   //使用栈来记录字符串结果,当遇到/../时,弹出栈  
   //如果用一个栈来一次存储各级路径的directory名字,然后重组,会简便一些,这也是文件路径简化类题目的常用思路。  
   //为了末尾可以顺序遍历栈重组path,我们不用传统的stack lib,而用vector来实现栈,这样可以方便顺序遍历。  
   string simplifyPath(string path) {  
     string result;  
     path.append("/");  
     vector<string> paths;  
     size_t pos = path.find_first_of("/");  
     size_t last = 0;  
     while (pos != string::npos) {  
       string substr = path.substr(last, pos - last);  
       if (substr == "..") {  
         if (!paths.empty()) {  
           paths.pop_back();  
         }  
       } else if (!substr.empty() && substr != ".") {  
         paths.push_back(substr);  
       }  
       last = pos + 1;  
       pos = path.find_first_of("/", last); // "last" position  
     }  
     if (paths.empty()) return "/";  
     for (auto s : paths) {  
       result += "/" + s;  
     }  
     return result;  
   }  
 };  
   
 class Solution {  
 public:  
   string simplifyPath(string path) {  
     vector<string> dirs;  
     path += '/';  
     string cur;  
     for (auto c : path) {  
       if (c != '/') {  
         cur += c;    
       } else {  
         if (cur == "..") {  
           if (!dirs.empty()) {  
             dirs.pop_back();  
           }  
         } else if(cur != "." && !cur.empty()){// cur != ""很重要.  
           dirs.push_back(cur);  
         }  
         cur.clear();  
       }  
     }  
     if (dirs.empty()) return "/";  
     string res;  
     for (auto dir : dirs) {  
       res += "/" + dir;  
     }  
     return res;  
   }  
 };  


No comments:

Post a Comment