描述
小东发现了一种叫“懒人笔记”的记笔记的偷懒的办法
例如:
5个a 写作 5a
banana 写作 b2(an)a
这样记笔记就可以省事多啦!
输入
每组数据一个字符串,表示小东使用“懒人笔记”记录的内容,字符串长度不超过100.
字符串只包含数字和小写字母以及括号.
输出
请你输出这个使用“懒人笔记”的方法记录的原字符串的内容.
输入样例 1
a4ple
输出样例 1
ap四个p(包括前面那个)le
输入样例 2
2(china)
输出样例 2
chinachina
输入样例 3
noi2(c2p3(c))
输出样例 3
noicpp3个c(包括前面那个)pp3个c
输入输出里的文字不要!
#include <iostream>
#include <string>
#include <stack>
using namespace std;
string process(string str) {
// 定义栈,用于存储字符串中的左括号
stack<int> st;
// 定义结果字符串
string result;
for (int i = 0; i < str.length(); i++) {
// 如果遇到左括号,则将位置压入栈中
if (str[i] == '(') {
st.push(i);
}
// 如果遇到右括号
else if (str[i] == ')') {
// 取出栈顶的左括号位置
int left = st.top();
st.pop();
// 取出左括号和右括号之间的字符串
string s = str.substr(left + 1, i - left - 1);
// 对字符串进行递归处理
s = process(s);
// 计算重复的次数
int repeat = 0;
for (int j = left - 1; j >= 0; j--) {
if (isdigit(str[j])) {
repeat = repeat * 10 + (str[j] - '0');
}
else {
break;
}
}
// 复制字符串
for (int j = 0; j < repeat; j++) {
result += s;
}
// 跳过括号内的字符串
i = left - 1;
}
// 如果当前字符是数字,则跳过
else if (isdigit(str[i])) {
continue;
}
// 其他字符直接添加到结果字符串中
else {
result += str[i];
}
}
// 返回结果字符串
return result;
}
int main() {
string str;
while (cin >> str) {
cout << process(str) << endl;
}
return 0;
}
网址:http://1.12.248.159/problem/031
#include <iostream>
#include <string>
using namespace std;
string decode(string s)
{
// 定义一个空字符串来保存解码后的字符串
string result;
// 循环处理字符串中的每一个字符
for (int i = 0; i < s.size(); i++)
{
// 如果是数字,则表示有重复字符
if (isdigit(s[i]))
{
// 计算重复的次数
int count = s[i] - '0';
// 如果后面的字符是'(',则表示有嵌套的括号
if (s[i + 1] == '(')
{
// 找到对应的右括号的位置
int j = i + 1;
int cnt = 1;
while (cnt > 0)
{
if (s[j] == '(')
cnt++;
if (s[j] == ')')
cnt--;
j++;
}
// 调用辅助函数来解码嵌套的括号
string t = decode(s.substr(i + 2, j - i - 3));
// 将解码后的字符串重复count次
while (count--)
result += t;
// 更新字符串的下标
i = j - 1;
}
else
{
// 否则,直接重复下一个字符count次
while (count--)
result += s[i + 1];
// 更新字符串的下标
i++;
}
}
else
{
// 如果是字母,直接添加到结果字符串中
result += s[i];
}
}
// 返回解码后的字符串
return result;
}
int main()
{
string s;
while (cin >> s)
{
cout << decode(s) << endl;
}
return 0;
}
望采纳。