Straightforward AC JAVA Solution with explanation


  • 0

    The basic idea is to convert the start time,end time ,and given list of time into equivalent long number, then compare these numbers to judge whether the given time falls into the range between start time and end time.

    public class LogSystem {
        HashMap<Integer,String> map = new HashMap<>();
        public LogSystem() {
            
        }
        
        public void put(int id, String timestamp) {
            map.put(id,timestamp); 
        }
        
        public List<Integer> retrieve(String s, String e, String gra) {
            int grade = 0;// only need to take care of substring, since according to the gra we do not need to compare the rest of the string
            switch(gra){
                case "Year":
                    grade += 4;
                    break;
                case "Month":
                    grade += 7;
                    break;
                case "Day":
                    grade += 10;
                    break;
                case "Hour":
                    grade += 13;
                    break;
                case "Minute":
                    grade += 16;
                    break;
                case "Second":
                    grade += 19;
                    break;
            }
            String ss =s.substring(0,grade);
            String es =e.substring(0,grade);
            String sss [] = ss.split(":");// get string of start time with year,month,day etc separately
            String ess [] = es.split(":");// get string of end time with year,month,day etc separately
            long start = Long.valueOf(sss[0]);
            long end = Long.valueOf(ess[0]);// because the year like 2017 takes 4 digits, so convert the year into long type at first, then since month,day,hour...etc only takes 2 digits so that we only need multiply 100 to get the final sum of original string
            for(int i = 1;i<sss.length;i++){
                start = start*100 + Long.valueOf(sss[i]);
                end = end*100 + Long.valueOf(ess[i]);
            }
            List<Integer> res = new ArrayList<>();
            for(Map.Entry<Integer,String> entry : map.entrySet()){
                String strs [] = entry.getValue().substring(0,grade).split(":");
                long num = Long.valueOf(strs[0]);
                for(int i = 1;i<strs.length;i++){
                    num = num*100 + Long.valueOf(strs[i]);
                }
                if(num<=end&&num>=start){
                    res.add(entry.getKey());// check whether the current number is >= start or <= end
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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