I split it in the reverse way. So all the following code should do reverse way.
1 class Solution { 2 public: 3 vector<string> splits(string s) { 4 vector<string> result; 5 int len = s.size(); 6 for (int i = len-1; i >= 0; i--) { 7 if (s[i] == ‘/‘) { 8 len = i; 9 } else if (i == 0 || s[i-1] == ‘/‘) { 10 result.push_back(s.substr(i, len-i)); 11 } 12 } 13 return result; 14 } 15 string simplifyPath(string path) { 16 if (path.size() == 0) return "/"; 17 vector<string> paths = splits(path.substr(1)); 18 stack<string> s; 19 string result; 20 for (int i = paths.size()-1; i >= 0; i--) { 21 if (!s.empty() && paths[i] == "..") { 22 s.pop(); 23 } else if (paths[i] != "." && paths[i] != "..") { 24 s.push(paths[i]); 25 } 26 } 27 if (s.empty()) return "/"; 28 while (!s.empty()) { 29 result = ‘/‘ + s.top() + result; 30 s.pop(); 31 } 32 return result; 33 } 34 };
LeetCode - Refresh - Simplify Path
原文:http://www.cnblogs.com/shuashuashua/p/4359832.html