STring II(模拟+栈)

时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
We have a string X, which has an even number of characters. Half the characters are ‘S’, and the other half are ‘T’.

Takahashi, who hates the string ‘ST’, will perform the following operation 10^10000 times:

Among the occurrences of ‘ST’ in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.
Find the eventual length of X.

Constraints
2≦|X|≦200,000
The length of X is even.
Half the characters in X are ‘S’, and the other half are ‘T’.

Partial Scores
In test cases worth 200 points, |X|≦200.
输入
The input is given from Standard Input in the following format:
X
输出
Print the eventual length of X.
样例输入 Copy

TSTTSS

样例输出 Copy

4

提示
In the 1-st operation, the 2-nd and 3-rd characters of ‘TSTTSS’ are removed. X becomes ‘TTSS’, and since it does not contain ‘ST’ anymore, nothing is done in the remaining 10^10000−1 operations. Thus, the answer is 4.
题目大意是从左到右找"ST"子串,如果有就将其去掉,如果没有就什么都不做,重复10^10000次。
一开始我用的是string容器中的substr函数,3次RE,然后换用erase函数,2次RE,上网百度了这两个函数的用法后仍然不知道错在哪里。。。
补题的时候发现这个题目的标签之一是栈,我记得之前做过一个类似的题目,就是遇到相异的立方体就移去,剩下的合并,问最后剩余多少块,和这个题目相似。因此对于这个题,我们可以从"ST"入手,如果栈顶元素是"S"且当前元素是"T",就弹栈,其余情况下(包括栈空时)压栈。

#include<cstdio>
#include<stack>
using namespace std;
stack<char>c;
char s[200005];
int main()
{
    int i;
    scanf("%s",s);
    for(i=0;s[i]!='\0';i++)
    {
        if(c.empty()||!(c.top()=='S'&&s[i]=='T'))c.push(s[i]);//栈空或不满足栈顶元素为"S"且当前元素为"T"
        else c.pop();//满足栈顶元素为"S"且当前元素为"T"
    }
    printf("%d",c.size());//栈的大小就是字符串的长度
    return 0;
}
/**************************************************************
    Language: C++
    Result: 正确
    Time:20 ms
    Memory:2396 kb
****************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值