Simplify Path Solutions in C++
Number 71
Difficulty Medium
Acceptance 32.7%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/simplify-path/// Author : Hao Chen// Date : 2014-10-09#include <iostream>#include <string>#include <vector>#include <sstream>using namespace std;vector<string> &split(const string &s, char delim, vector<string> &elems) {stringstream ss(s);string item;while (getline(ss, item, delim)) {elems.push_back(item);}return elems;}vector<string> split(const string &s, char delim) {vector<string> elems;split(s, delim, elems);return elems;}string simplifyPath(string path) {string result;vector<string> elems = split(path, '/');int ignor = 0;for(int i=elems.size()-1; i>=0; i--) {if (elems[i]=="" || elems[i]=="." ){continue;}if (elems[i]==".."){ignor++;continue;}if (ignor>0){ignor--;continue;}if (result.size()==0){result = "/" + elems[i];}else{result = "/" + elems[i] + result;}}return result.size() ? result : "/";}int main(int argc, char** argv){string path("/a/./b/../../c/");if (argc > 1 ){path = argv[1];}cout << path << " : " << simplifyPath(path) << endl;}
C++ solution by pezy/LeetCode
#include <string>using std::string;#include <vector>using std::vector;#include <sstream>using std::istringstream;class Solution {public:string simplifyPath(string path) {string ret, tmp;vector<string> stack;for ( istringstream iss(path); getline(iss, tmp, '/'); ) {if (tmp == ".." && !stack.empty()) stack.pop_back();else if (tmp == "." || tmp == ".." || tmp == "") continue;else stack.push_back(tmp);}for (auto str : stack) { ret += "/" + str; }return ret.empty() ? "/" : ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/simplify-path//// Author : liuyubobobo/// Time : 2019-02-10#include <iostream>#include <vector>using namespace std;/// Using Stack/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:string simplifyPath(string path) {vector<string> stack;for(int start = 1, i = 1; i <= path.size(); i ++)if(i == path.size() || path[i] == '/'){string f = path.substr(start, i - start);if(f.size()){if(f == ".."){if(stack.size()) stack.pop_back();}else if(f != ".") stack.push_back(f);}start = i + 1;}string res = "";for(string e: stack)res += "/" + e;return res == "" ? "/" : res;}};int main() {return 0;}