网易游戏笔试2015—字符串压缩

题目:

对字符串压缩格式包含两种类型

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—字符串压缩
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值