Simple Text Editor

  • + 0 comments
    #include <bits/stdc++.h>
    #define lli long long int
    using namespace std;
    
    int main() {
    
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        
        stack<char> s;
        stack<string> undo;
        
        lli tc;
        cin >> tc;
        while(tc--) {
            lli x;
            cin >> x;
            if (x == 1) {
                // insert
                string v;
                cin >> v;
    
                string temp = "";
                if (!undo.empty()) {
                    temp = undo.top();
                }
                for (int i = 0; i < v.length(); i++) {
                    temp += v[i];
                    s.push(v[i]);
                }
                undo.push(temp);
            } else if (x == 2) {
                if (s.empty()) continue;
                // delete
                lli y;
                cin >> y;
                while(y--) {
                    s.pop();
                }
                string ab = "";
                stack<char> temp;
                temp = s;
                while(!temp.empty()) {
                    ab += temp.top();
                    temp.pop();
                }
                if (ab.length() > 0) reverse(ab.begin(), ab.end());
                undo.push(ab);
            } else if (x == 3) {
                if (s.empty()) continue;
                // print
                lli y;
                cin >> y;
                string temp = undo.top();
                cout << temp[y-1] << "\n";
            } else {
                // undo
                if (!undo.empty()) {
                    undo.pop();
                    string temp = "";
                    if (!undo.empty()) temp = undo.top();
                    s = stack<char>();
                    for (auto it: temp) {
                        s.push(it);
                    }
                }
            }
        }
        
        return 0;
    }