题目:
对字符串压缩格式包含两种类型
1.字母+数字
2.括号+数字
例如:”A5″表示5个连续的”A”,”(A2B)3″表示3个连续的”A2B”,实际的输入会包含这两种格式的嵌套。
示例:
测试输入:(4表示接下来有4组输入测试数据)
4
(AA)2A
((A2B)2)2G
WANGYI
A2BC4D2
测试输出:
5
13
6
9
解析:
利用栈求解,遇到’(‘,入栈一个整数0,作为新的栈头,用栈头记录当前’(‘到遇这个’(‘匹配的’)'其中的字符串长度。
#include <iostream>
#include <stack>
#include <string>
#include <fstream>
using namespace std;
int CharType(char c)
{
if (c == '(')
return -1;
if (c == ')')
return -2;
if (int(c) > 60)
return -(c - 'A') - 3;
else
return c - '0';
}
int CharLength(string s, int point)
{
int result = 0;
while (point + 1 < s.length()&&CharType(s[point+1])>=0)
{
result = result * 10 + CharType(s[point + 1]);
point++;
}
return result == 0 ? 1 : result;
}
int main()
{
ifstream in(".\\input.txt");
cin.rdbuf(in.rdbuf());
int n;
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++)
{
string input;
cin >> input;
stack<int> s;
s.push(0);
for (int k = 0; k < input.length(); k++)
{
int type = CharType(input[k]);
if (type >= 0)
continue;
if (type==-1)
{
s.push(0);
continue;
}
if (type<-2)
{
s.top() += CharLength(input, k);
}
if (type==-2)
{
int temp = s.top();
s.pop();
s.top() += temp* CharLength(input, k);
}
}
cout << s.top() << endl;
}
system("pause");
return 0;
}
网易游戏笔试2015—字符串压缩