不准访问
- 积分
- 3455
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-11-14
- 最后登录
- 1970-1-1
|
能写码就不bb 写了一个有点繁琐的
- class ExpandString {
- public:
- vector<string> tokenize(string & str) {
- cout << "TOK: " << str << endl;
- vector<string> tokens;
- str.push_back(',');
- int start = 0;
- for (int i = 0; i < str.size(); ++i) {
- if (isalpha(str[i])) {
- continue;
- } else if (str[i] == '{') {
- int cnt = 0;
- while (true) {
- if (str[i] == '{') {
- ++cnt;
- } else if (str[i] == '}') {
- --cnt;
- }
- if (cnt == 0) {
- break;
- }
- ++i;
- }
- } else if (str[i] == ',') {
- string w = str.substr(start, i - start);
- start = i + 1;
- vector<string> res = expand(w);
- copy(res.begin(), res.end(), back_inserter(tokens));
- }
- }
- return tokens;
- }
- vector<string> expand(string & str) {
- cout << "EXP: " << str << endl;
- auto loc = str.find('{');
- if (loc == string::npos) {
- return {str};
- }
- vector<string> out = {""};
- for (int i = 0; i < str.size(); ++i) {
- if (isalpha(str[i])) {
- int e = i;
- while (e < str.size() && isalpha(str[e])) {
- ++e;
- }
- string w = str.substr(i, e - i);
- for (int j = 0; j < out.size(); ++j) {
- out[j] = out[j] + w;
- }
- i = e - 1;
- } else {
- // bracket
- int cnt = 0;
- int e = i;
- while (true) {
- if (str[e] == '{') {
- ++cnt;
- } else if (str[e] == '}') {
- --cnt;
- }
- if (cnt == 0) {
- break;
- }
- ++e;
- }
- string w = str.substr(i + 1, e - i - 1);
- vector<string> ws = tokenize(w);
- vector<string> base;
- base.swap(out);
- for (auto & s1: base) {
- for (auto & s2: ws) {
- out.push_back(s1 + s2);
- }
- }
- i = e;
- }
- }
- return out;
- }
- };
复制代码
Test Case
- int main() {
- string input = "{x,y}a{b,c,e{d,f}}";
- ExpandString es;
- vector<string> result = es.expand(input);
- for (auto s: result) {
- cout << s << " ";
- }
- cout << endl;
- }
复制代码
OUTPUT:
- EXP: {x,y}a{b,c,e{d,f}}
- TOK: x,y
- EXP: x
- EXP: y
- TOK: b,c,e{d,f}
- EXP: b
- EXP: c
- EXP: e{d,f}
- TOK: d,f
- EXP: d
- EXP: f
- xab xac xaed xaef yab yac yaed yaef
复制代码
|
|