礼盒问题

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>

using namespace std;

struct Node
{
	int is_box;
	string item;
	vector <struct Node *>childs;
};

void splie_contents(string str, vector <string>& contents)
{
	int pos = 0;
	int start;
	int end;
	stack <int> st;

	while(pos < str.size()) {
		pos = str.find(',');
		if(pos == string::npos) {
			contents.push_back(str);
			break;
		} else {
			contents.push_back(str.substr(0, pos));
		}

		pos++;
		if(str[pos] == '[') {
			start = pos;
			end = start+1;
			st.push(start);

			while(!st.empty() && end < str.size()) {
				if(str[end] == '[') {
					st.push(end);
				} else if(str[end] == ']') {
					st.pop();
				}

				end++;
			}

			contents.push_back(str.substr(start, end-start));
			pos = end+1;
		}

		if(pos < str.size()) {
			str = str.substr(pos);
		}
	}
}

struct Node *build_tree(string str)
{
	struct Node *root;
	struct Node *child;
	vector <string> contents;
	int pos = 0;

	cout << "build_tree: " << str << endl;

	root = new struct Node;

	/*items*/
	if(str[0] != '[') {
		root->is_box = 0;
		root->item = str;
		return root;
	}

	/*empty box*/
	if(str[0] == '[' && str[1] == ']') {
		root->is_box = 1;
		return root;
	}

	root->is_box = 1;

	/*split all items*/
	splie_contents(str.substr(1, str.size() - 2), contents);
	for(int i=0; i<contents.size(); i++) {
		cout << contents[i] << " ";
	}
	cout << endl;

	for(vector <string>::iterator it = contents.begin(); it < contents.end(); it++) {
		cout << *it << " ";
		child = build_tree(*it);
		root->childs.push_back(child);
	}

	cout << endl;

	return root;
}

void print_tree(struct Node *root)
{
	queue <struct Node *> que;
	struct Node *node;
	struct Node *flag;

	que.push(root);
	flag = root;

	while(!que.empty()) {
		node = que.front();

		if(!node->is_box) {
			cout << node->item << " ";
		} else {
			cout << "[] ";
		}

		if(node == flag) {
			if(!node->childs.empty()) {
				flag = node->childs[node->childs.size()-1];
			}

			cout << endl;
		}

		for(vector <struct Node*>::iterator it = node->childs.begin(); it<node->childs.end(); it++) {
			que.push(*it);
		}

		que.pop();
	}
}

int main(int argc, char **argv)
{
	//string str("[T-shirt,[doll,[dog,cat],[]]]");
	string str("[doll,[dog,cat],[]]");
	struct Node *root;

	root = build_tree(str);
	print_tree(root);

	return 0;
}

posted @ 2020-02-03 23:19  joechow  阅读(86)  评论(0)    收藏  举报