Description
Give you a string S consist of 'a', 'b', 'c'. You can change the string with the follow rule:
1.replace two continuous difference char to a single char.
2.there are 6 replace rules: "ab" - > "c", "ba" -> "c", "bc" -> "a", "cb" -> "a", "ac" -> "b", "ca" -> "b"
Can you tell me the minimum length of S after several replacement operation?
Input
The first line contain an integer T(1 <= T <= 10), indicate the number of testcase.
The next T lines each contain a string S(1 <= |S| <= 200), the string S only consist of three char 'a', 'b', 'c'.
Output
T lines, for each line, print the minimum length of string S.
Sample Input
4 aaaaa abc abcabc aabbc
Sample Output
5 2 2 1
Hint
"aaaaa" -> "aaaaa"
"abc" -> "aa"
"abcabc" -> "abcaa" -> "abba" -> "cba" -> "cc"
"aabbc" -> "aaba" -> "aca" -> "ba" -> "c"
一开始觉得好烦,不过后来发现用stack可以做,做完wa了一次,发现hint那个是从最后开始扫的,改了下就AC了
#include <iostream>
#include <cmath>
#include <stack>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--){
string str;
cin >> str;
int len=str.length();
stack <char> ch;
for(int i=len-1; i >= 0; --i){
if(ch.empty()==true){
ch.push(str[i]);
}
else{
if(str[i]==ch.top()){
ch.push(str[i]);
}
else{
char k=str[i];
while(k!=ch.top()){
if(int(k+ch.top())==195){
k='c';
ch.pop();
}
else if(int(k+ch.top())==196){
k='b';
ch.pop();
}
else if(int(k+ch.top())==197){
k='a';
ch.pop();
}
if(ch.empty()) break;
}
ch.push(k);
}
}
}
cout << ch.size() << endl;
}
}