[681. Next Closest Time] C++_AC


  • 0
    class Solution {
    public:
    string nextClosestTime(string time) {
        vector<int> vec;
        for(int i = 0; i < time.size(); ++i){
            if(time[i] != ':'){
                vec.push_back(time[i] - '0');
            }
        }
        sort(vec.begin(), vec.end());
        for(int i = 4; i >= 0; --i){
            if(i == 2) continue;
            for(int j = 0; j < 4; ++j){
                if(vec[j] > (time[i] - '0')){
                    if(i == 0 && vec[j] > 2) break;
                    if(i == 3 && vec[j] > 5) break;
                    if(i == 1 && vec[j] > 3 && time[0] - '0' > 1) break;                    
                    time[i] = vec[j] + '0';
                    int temp = i + 1;
                    while(temp < time.size()){
                        time[temp] = vec[0] + '0';
                        temp++;
                    }
                    time[2] = ':';
                    return time;
                }
            }
        }
        for(int i = 0; i < time.size(); ++i){
            if(time[i] != ':'){
                time[i] = vec[0] + '0';
            }
        }
        return time;
    }
    };

Log in to reply
 

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