签到题
东东有一个字符串X,该串包含偶数个字符,一半是 S 字符,一半是 T 字符
东东可以对该字符串执行 1e10000次操作:如果存在 ST 是该串的子串,则删除掉最左边的 ST。
即 TSTTSS⇒TTSS、SSSTTT⇒SSTT⇒ST⇒空
Input
(2 ≦ |X| ≦ 200,000)
Output
输出最终串的长度
Sample Input 1
TSTTSS
Sample Output 1
4
问题分析
题目思路比较简单,遍历数组,删除掉’TS’子串即可。但是操作次数很多,如果直接循环会超时。
因为栈具有FILO的特点,栈顶是最后放入的元素。因此改用一个栈,在遍历过程中将不是‘T’的字符放入栈中,每遇到’T’就弹出栈顶,如果栈顶是’S’,说明这个子串要删掉,size-2.
代码实现
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
string a;
cin>>a;
int sz= a.size();
stack<char> st;
for ( int i = 0 ; i < a.size() ; i ++ )
{
if ( a[i] == 'T' )
{
if ( !st.empty() )
{
if (st.top() == 'S' )
{
sz -= 2 ;
st.pop() ;
}
}
else
st.push(a[i]) ;
}
else
st.push(a[i]) ;
}
cout << sz << endl ;
return 0 ;
}