c++ switch and case


  • 0
    B

    use case fall through feature, so we only need to change some char for input agr. So we can reduce substr operation

    class LogSystem {
    public:
        //key: timestamp in string
        //val: id
        map<string,int> pool;
        LogSystem() {
        }
        
        void put(int id, string timestamp) {
            pool[timestamp] = id;
        }
        
        vector<int> retrieve(string s, string e, string gra) {
            switch (getGra(gra))
            {//fall through cases
                case 1:
                    s[5] = s[6] = '0';
                    e[5] = e[6] = '9';
                case 2:
                    s[8] = s[9] = '0';
                    e[8] = e[9] = '9';
                case 3:
                    s[11] = s[12] = '0';
                    e[11] = e[12] = '9';
                case 4:
                    s[14] = s[15] = '0';
                    e[14] = e[15] = '9';
                case 5:
                    s[17] = s[18] = '0';
                    e[17] = e[18] = '9';
                default:
                    s[20] = s[21] = '0';
                    e[20] = e[21] = '9';
            }
            auto start = pool.lower_bound(s);
            auto end = pool.upper_bound(e);
            vector<int>ans;
            while(start != end)
            {
                ans.push_back(start -> second);
                start++;
            }
            return ans;
        }
        
        int getGra( const string & s )
        {
            if(s == "Year")
                return 1;
            else if( s == "Month")
                return 2;
            else if( s == "Day")
                return 3;
            else if( s == "Hour")
                return 4;
            else if( s == "Minute")
                return 5;
            else
                return 6;
        }
    };
    
    /**
     * Your LogSystem object will be instantiated and called as such:
     * LogSystem obj = new LogSystem();
     * obj.put(id,timestamp);
     * vector<int> param_2 = obj.retrieve(s,e,gra);
     */

Log in to reply
 

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