C++ straight-forward solution


  • 0
    M
        char c[5];
        int t=0, res=INT_MAX;
        string nextClosestTime(string time) {
            c[0]=time[0];
            c[1]=time[1];
            c[2]=time[3];
            c[3]=time[4];
            t=stoi(time.substr(0, 2))*60+stoi(time.substr(3)); 
            BT("");
            if(res>=1440) res-=1440;
            string h=to_string(res/60), m=to_string(res%60);
            if(h.size()<2) h="0"+h;
            if(m.size()<2) m="0"+m;
            return h+":"+m;
        }
        
        void BT(string s) {
            if(s.size()==4) {
                int hour=stoi(s.substr(0, 2)), min=stoi(s.substr(2));
                if(hour<=24&&min<=59) {
                    int num=hour*60+min;
                    if(num<=t) num+=1440;
                    if(abs(t-num)<abs(res-t)) res=num;
                }
                return;
            }
            for(int i=0;i<4;i++) {
                s.append(1, c[i]);
                BT(s);
                s.pop_back();
            }
        }

Log in to reply
 

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