I was solving a Stack problem in which I needed to make a Simple Text Editor, But in some test cases with Queries input > 10^6 my code is showing an error of Time limit exceeded
Here is the Problem Statement In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following types:
- append - Append string W to the end of S.
- delete - Delete the last k characters of S.
- print - Print the kth character of S.
- undo - Undo the last (not previously undone) operation of type 1 or 1, reverting S to the state it was in prior to that operation.
Here is my code:-
#include <cmath>
#include <cstdio>
#include <vector>
#include<stack>
#include <iostream>
#include<string>
#include<sstream>
#include <algorithm>
using namespace std;
void TextEditor(vector<pair<int, string>>& v) {
auto it = v.begin();
int x;
stack<string>s;
string inputString="";
s.push(inputString);
while (it != v.end()) {
if (it->first == 1) {
string topString =s.top();
inputString = it->second;
s.push(topString.append(inputString));
}
else if(it->first==2){
stringstream ss(it->second);
ss >> x;
string del;
del = s.top();
if (del != "") {
int idx = del.length() - x;
s.push(del.erase(idx));
}
}
else if (it->first == 3) {
stringstream ss(it->second);
ss >> x;
string print;
print = s.top();
cout << print[x-1] <<endl;
}
else if (it->first == 4) {
s.pop();
}
it++;
}
}
int main() {
int Q,t,ti;
string s;
cin >> Q;
vector<pair<int, string>>v;
for (int i = 0; i < Q; i++) {
cin >> t;
if (t == 4) {
v.push_back(make_pair(t, "0"));
}
else {
cin >> s;
v.push_back(make_pair(t, s));
}
}
TextEditor(v);
return 0;
}
in the code used stl libraries to solve this problem but it is showing time limit exceeds the error. Can anybody help me optimize the code?
question from:https://stackoverflow.com/questions/65646205/optimizing-the-simple-text-editor