Created
January 28, 2013 13:44
-
-
Save pdu/4655597 to your computer and use it in GitHub Desktop.
Given an absolute path for a file (Unix-style), simplify it. For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c" http://leetcode.com/onlinejudge#question_71
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void update(vector<string>& s, const string& t) { | |
| if (t == ".") | |
| ; | |
| else if (t == "..") { | |
| if (!s.empty()) | |
| s.pop_back(); | |
| } | |
| else | |
| s.push_back(t); | |
| } | |
| class Solution { | |
| public: | |
| string simplifyPath(string path) { | |
| vector<string> s; | |
| int prev = -1; | |
| for (int i = 0; i < path.length(); ++i) | |
| if (path[i] == '/') { | |
| if (prev != -1 && prev != i) | |
| update(s, path.substr(prev, i - prev)); | |
| prev = i + 1; | |
| } | |
| if (prev != path.length()) | |
| update(s, path.substr(prev, path.length() - prev)); | |
| if (s.empty()) | |
| return "/"; | |
| string ret; | |
| for (int i = 0; i < s.size(); ++i) | |
| ret.append("/").append(s[i]); | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment