练习题3-字符串解码

原题目:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = “3[a]2[bc]”, 返回 “aaabcbc”.
s = “3[a2[c]]”, 返回 “accaccacc”.
s = “2[abc]3[cd]ef”, 返回 “abcabccdcdcdef”.

思路:
用了递归的方法
1.用for循环和if判断是数字还是字母,如果是数字,进入转换函数。如果是字母,拼接在后面。
2.判断数字后的字母,并将其字母加在字符串,遇到下一个数字,就将字符按照重复次数(这部分用迭代)加载前面字符串上。

代码

#include <iostream>
#include "stdlib.h"
#include "string.h"
#include "sstream"
#include "cstdlib"
using namespace std;   
string s3;//存储每次数字后面字母
string s7;//递归函数返回的字符串
string s9;//记录每次遍历到的字母位置
int t=0;  //t就是字母需要重复的次数
int t2 = 0;	//因为字母读入时,已经读入一遍,所以应该用flag判断是否让遍历数减一
int t3 = 0;//遍历的下标
int t4 = 0;//记录重复次数
bool flag = false;//用于判断有无嵌套
bool flag2 = false;
//用来判断是否退出嵌套
string shuzi(char *s1, int t)
{
	int t1;
	t2 = t;
	while (*s1 != ']')
	{
		if (*s1 == ']')
		{
			t2 = t - 1;
		}
		if (flag == true)
		{
			s1 = &s9[0];
		}
		if (*s1 >= 'a'&&*s1 <= 'z')
		{
			s3 += *s1;
			s1++; 
			t3++;
			s9 = s1;
		}
		if (*s1 >= '1'&&*s1 <='9')
		{
			t1 = atoi(s9.c_str());
			s1 = s1+2;
			t3 = t3 + 2;
			s7 += s3;
			s9 = s1;
			s3.clear();
			flag = true;
			s3 = shuzi(s1, t1);
		}
	}
	for (int i = 0; i < t2; i++)
	{
		s7 += s3;
	}
	s3.clear();
	flag2 = true;
	t4++;
	return s7;
}
string decodeString(string s) {
	char *s1;  //用来标记数字后面的字母位置
	string s8;//用来存储【】前面数字并且需要转换成int型
	string s4;//用来存储最终的解码字符串
	for (int i = 0; i < s.length(); i++)
	{
		if (s[i] >= '1'&&s[i] <= '9')
		{
			s8 = &s[i];
			s1 = &s[i + 2];
			t = atoi(s8.c_str());
			s4=shuzi(s1, t);
			i=2*t4+t3;
			while (flag2!=true);
		}
		if (s[i] >= 'a'&&s[i] <= 'z')
		{
			s4 += s[i];
			flag2 = false;
		}
		t3++;
	}
	return s4;
}
	int main()
	{
		string s5;
		string s6= "2[abc]3[cd]ef";
		s5 = decodeString(s6);
		printf("%s", s5);
	}

没测试过,可能其他的测试用例有错误。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值