Small c's notebook (stack)

The problem comes from https://ac.nowcoder.com/acm/problem/15975

stack<string> c;
int main(){
    
    
    ios::sync_with_stdio(false);
    int q;
    cin>>q;
        string s;
        c.push(s);
        while(q--){
    
    
            int t;
            cin>>t;
            if(t==1){
    
    
                string str;
                cin>>str;
                s=s+str;
                c.push(s);
            }else if(t==2){
    
    
                int k;
                cin>>k;
                s=s.substr(0,s.size()-k);
                c.push(s);
            }else if(t==3){
    
    
                int k;
                cin>>k;
                cout<<s[k-1]<<endl;
            }else if(t==4){
    
    
                c.pop();
                s=c.top();
            }
        }
	return 0;
}

Although it is said that the problem is the stack, the stack is only used in requirement four. In order to facilitate the cancellation, the content of requirement one and two needs to be stored in the stack first; explain the code, requirement one, open a string, and add it with the string Fill in; the second is to delete, using string interception, substr(5,3) means that the subscript starts from 5 and intercepts 3 digits . Delete is to delete the content except for the intercepted part. The length problem is solved with one hand size().

 ios::sync_with_stdio(false);

In this way, the synchronization of cin and stdin can be cancelled, and the speed of cin and scanf is not much different.
Knowledge point, a space in the stack can store a string.
Summary: string usage
1. string s,k; s=s+k;Strings can be added directly.
2. string s;s.substr(0,3);Intercept the three characters starting from zero in s.
3. s.erase(s.begin());Delete the first element to
s.erase(--s.end());delete the last element.

Guess you like

Origin blog.csdn.net/iuk11/article/details/106771712