Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger class:
Logger() Initializes the logger object.
bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp, otherwise returns false.
Every timestamp will be passed in non-decreasing order (chronological order).
1 <= message.length <= 30
At most 104 calls will be made to shouldPrintMessage.
Solutions
Solution 1
1 2 3 4 5 6 7 8 91011121314151617181920212223
classLogger:def__init__(self):""" Initialize your data structure here. """self.limiter={}defshouldPrintMessage(self,timestamp:int,message:str)->bool:""" Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. """t=self.limiter.get(message,0)ift>timestamp:returnFalseself.limiter[message]=timestamp+10returnTrue# Your Logger object will be instantiated and called as such:# obj = Logger()# param_1 = obj.shouldPrintMessage(timestamp,message)
classLogger{privateMap<String,Integer>limiter;/** Initialize your data structure here. */publicLogger(){limiter=newHashMap<>();}/** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */publicbooleanshouldPrintMessage(inttimestamp,Stringmessage){intt=limiter.getOrDefault(message,0);if(t>timestamp){returnfalse;}limiter.put(message,timestamp+10);returntrue;}}/** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */
/** * Initialize your data structure here. */varLogger=function(){this.limiter={};};/** * Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. * @param {number} timestamp * @param {string} message * @return {boolean} */Logger.prototype.shouldPrintMessage=function(timestamp,message){constt=this.limiter[message]||0;if(t>timestamp){returnfalse;}this.limiter[message]=timestamp+10;returntrue;};/** * Your Logger object will be instantiated and called as such: * var obj = new Logger() * var param_1 = obj.shouldPrintMessage(timestamp,message) */