2018年10月25日 星期四

[LeetCode] 681. Next Closet Time


  • Problem: 681. Next Closet Time 下個最接近的時間
  • Limitation: 只能用原本時間的 digits, 可以重複
  • Concept: 
    • string/char/time 操作
    • 可以直接暴力的使用累加來比對是否符合條件, 因為最大值僅 60 * 24 (=1440)
    • Note: includes 的 parameter 僅能用以排序的 container, e.g. set
  • class Solution {
    public:
        string nextClosestTime(string time) {
            string nextTime = time;
            
            // brute force to incremental check
            set setTimeChar(time.begin(), time.end());
    
            int hours = stoi(time.substr(0, 2));
            int mins = stoi(time.substr(3, 2));
    
            const int MAX_NEXT_TIME = 60 * 24;
            
            for (int i = 0; i < MAX_NEXT_TIME; i++) {
                if(++mins >= 60) {
                    mins -= 60;
                    ++hours;
                    if (hours >= 24)
                        hours -= 24;
                };
                
                const int TIME_LEN = 5;
                char buf[TIME_LEN];
                sprintf(buf, "%02d:%02d", hours, mins);
                set setNextTimeChar(buf, buf + TIME_LEN);
                if (includes(setTimeChar.begin(), setTimeChar.end(), setNextTimeChar.begin(), setNextTimeChar.end()))
                    return string(buf);
            }
            return time;
        }
    };
    

沒有留言:

張貼留言