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.
importjava.io.*;importjava.util.*;classSolution{staticclassPair{//to store the write and delete commands and operated strings in a stackintopr;Stringtext;Pair(intop,Strings){opr=op;text=s;}}publicvoidSimpleTextEditor(){Scannersc=newScanner(System.in);//first line of input has length of string arrayintn=Integer.parseInt(sc.nextLine().trim());String[]operations=newString[n];for(inti=0;i<n;i++)operations[i]=sc.nextLine();//create stack to store operations of write and delete and string builder to store textStack<Pair>st=newStack<>();StringBuilderdoc=newStringBuilder();for(inti=0;i<n;i++){intcommand=operations[i].charAt(0)-'0';if(command==1)//append{Stringtext=operations[i].substring(2);st.push(newPair(1,text));doc.append(text);}elseif(command==2)//delete{intlength=Integer.parseInt(operations[i].substring(2));intstartDelete=doc.length()-length;intendDelete=doc.length();st.push(newPair(2,doc.substring(startDelete)));doc.delete(startDelete,endDelete);}elseif(command==3)//print{intindex=Integer.parseInt(operations[i].substring(2))-1;System.out.println(doc.charAt(index));}elseif(command==4)//undo{Pairlast=st.pop();if(last.opr==1){inttextlength=last.text.length();intdeleteStart=doc.length()-textlength;doc.delete(deleteStart,doc.length());}elseif(last.opr==2){Stringdeleted=last.text;doc.append(deleted);}}elseSystem.out.println("INVALID");}}}publicclassMain{publicstaticvoidmain(Stringargs[]){Solutionob=newSolution();ob.SimpleTextEditor();}}
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 →
STACK AND STRINGBUILDER SOLUTION