We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicclassSolution{publicstaticclassOperation{inttype;Objectarg;Objectresult;publicstaticOperationparse(Stringcontent){Operationoperation=newOperation();operation.type=Integer.parseInt(content.charAt(0)+"");// has argswitch(operation.type){case1:{operation.arg=content.substring(2);break;}case2,3:{operation.arg=Integer.valueOf(content.substring(2));break;}case4:{break;}default:thrownewIllegalArgumentException();}returnoperation;}}publicstaticclassTextEditor{privatefinalStringBuildercontent=newStringBuilder();privatefinalStack<Operation>actions=newStack<>();publicvoidcommand(Operationoperation){if(operation==null){return;}switch(operation.type){case1:{this.actions.push(operation);this.append((String)operation.arg);break;}case2:{operation.result=this.delete((Integer)operation.arg);this.actions.push(operation);break;}case3:{this.print((Integer)operation.arg);break;}case4:{this.undo();break;}}}privatevoidappend(Strings){if(s==null){return;}this.content.append(s);}privateStringdelete(intk){if(k<0){thrownewIllegalArgumentException();}intlength=this.content.length();intdeleteFrom=length-k;StringdeletedContent=this.content.substring(deleteFrom,length);this.content.delete(deleteFrom,length);returndeletedContent;}privatevoidprint(intk){if(k<0||k>this.content.length()){return;}System.out.println(this.content.charAt(k-1));}privatevoidundo(){if(this.actions.isEmpty()){return;}Operationoperation=this.actions.pop();if(operation.type==1){Stringcontent=(String)operation.arg;this.delete(content.length());}elseif(operation.type==2){StringdeletedContent=(String)operation.result;this.append(deletedContent);}}}publicstaticvoidmain(String[]args){finalTextEditortextEditor=newTextEditor();finalScannerscanner=newScanner(System.in);finalintq=scanner.nextInt();scanner.nextLine();for(inti=0;i<q;i++){Stringcommand=scanner.nextLine();Operationoperation=Operation.parse(command);textEditor.command(operation);}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Simple Text Editor
You are viewing a single comment's thread. Return to all comments →
Java