描述
给出一个表达式 s,此表达式包括数字,字母以及方括号。在方括号前的数字表示方括号内容的重复次数(括号内的内容可以是字符串或另一个表达式),请将这个表达式展开成一个字符串。
数字只能出现在“[ ]”前面。
您在真实的面试中是否遇到过这个题?
样例
样例1
输入: S = abc3[a]
输出: “abcaaa”
样例2
输入: S = 3[2[ad]3[pf]]xyz
输出: “adadpfpfpfadadpfpfpfadadpfpfpfxyz”
#include<iostream>
#include<regex>
#include<string>
using namespace std;
class Solution {
public:
/**
* @param s: an expression includes numbers, letters and brackets
* @return: a string
*/
//由内到外分解
string expressionExpand(string &s) {
// write your code here
regex patt("\\d+\\[\\w+\\]");//正则表达式 “数字[字母 ]”
smatch matchRes;
while (regex_search(s, matchRes, patt))
{
string tmp = matchRes[0];
string::size_type pos = tmp.find("[");
int k;//数字部分
string extenStr;
if (pos != string::npos)
{
k = stoi(tmp.substr(0, pos));
}
string sstr = tmp.substr( pos + 1, tmp.size() - pos - 2);
for (int i = 0; i<k; i++)
extenStr += sstr;
string::size_type subPos=s.find(tmp);
if(subPos!=string::npos)
{
s.replace(s.begin()+subPos,s.begin()+subPos+tmp.size(),extenStr);
}
}
return s;
}
};