Why my code got wrong after I made a seemingly-right change?


  • 0
    K

    I got AC when running the following code. Note that I comment out if(end>start+1) However if I didn't, then I got error message:

    Input:
    "/.../"
    Output:
    "/.../..."
    Expected:
    "/..."
    

    Any help is appreciated. Thanks!

    class Solution {
    public:
        string simplifyPath(string path) {
            stack<string> st;
            string s, res;
            int len = path.size();
            int start=0, end=0;
            while(start<len)
            {
                end = start+1;
                while(end<len && path[end]!='/')
                    ++end;
                // if(end>start+1)
                    s = path.substr(start+1, end-start-1);
                if(s.size()>0)
                {
                    if(s==".." && !st.empty())
                            st.pop();
                    else if(s!=".." && s!=".")
                        st.push(s);
                }
                start = end;
            }
            if(st.empty())
                return "/";
            while(!st.empty())
            {
                res = "/" + st.top() + res;
                st.pop();
            }
            return res;
        }
    };

Log in to reply
 

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