C++ implementation


  • 5
    2
    class Solution {
    public:
        string simplifyPath(string path) {
            vector<string> st;
            vector<string> nodes;
            string result;
            split(path, '/', nodes);
            for(auto node : nodes) {
                //empty or only '.' path no change
                if(node == "" || node == ".")  continue;
                //go back to the upper directory
                if(node == ".." && !st.empty())  st.pop_back();
                //push back the current directory
                else if(node != "..")  st.push_back(node);
            }
            for(auto it : st) result += "/" + it;
            return result.empty() ? "/" : result;
        }
        
        void split(string s, char delim, vector<string>& nodes) {
            string temp;
            stringstream ss(s);
            while(getline(ss, temp, delim)) {
                nodes.push_back(temp);
            }
        }
    };

  • 0

    I am a totally newer for C++(Due to looking for Internship, I want to learn some knowledge about C++(only know a little bit C)). Today, I just register my first account at Leetcode.

    However, I did not know the following is correct or not. Hopefully, it can help somewhat. Good Luck~

    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>   //add header;
    using namespace std;
    
    class Solution {
    public:
         string simplifyPath(string path) {
             vector<string> st;
             vector<string> nodes;
             string result;
             split(path, '/', nodes);
             for(auto node : nodes) {
                 //empty or only '.' path no change
                  if(node == "" || node == ".")  continue;
                  //go back to the upper directory
                  if(node == ".." && !st.empty())  st.pop_back();
                  //push back the current directory
                 else if(node != "..")  st.push_back(node);
             }
             for(auto it : st) result += "/" + it;
             return result.empty() ? "/" : result;
          }
    
         void split(string s, char delim, vector<string>& nodes) {
             string temp;
             stringstream ss;    //here
             ss.str(s);                //here
             while(getline(ss, temp, delim)) {
                  nodes.push_back(temp);
            }
         }
     };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.