字符串入栈出栈

设字符串source,依次进入一个初始为空的栈,在入栈的过程中可以出栈,得到一个出栈字符串dest。设计程序,给出所有可能的入栈出栈的过程。假设入栈用i表示,出栈用o表示。 如: source为:balama dest为:balama 则输出为: i o i i i o o i i o o o  i o i i i o o o i o i o  i o i o i o i i i o o o  i o i o i o i o i o i o   source为:value dest为:lvaeu 则输出为: 输入错误
#include 
#include 
#include 

using namespace std;

const bool PUSH = true;
const bool POP = false;

class Question
{
public:
	void input();
	void solve(unsigned int source_i = 0, unsigned int dest_i = 0, unsigned int op_i = 0);
	Question();
	~Question();
	bool success;
private:
	stack s;
	bool *operations;
	string source, dest, result;
};

void Question::input()
{
	cout << "请输入source:";
	getline(cin, source);
	operations = new bool[2 * source.size()];
	cout << "请输入dest:";
	getline(cin, dest);
	result = dest;
}

void Question::solve(unsigned int source_i, unsigned int dest_i, unsigned int op_i)
{
	char temp;
	if (dest_i == dest.size())
	{
		if (dest == result)
		{
			success = true;
			for (unsigned int i = 0; i < op_i; i++)
				cout << (operations[i] ? 'i' : 'o');
			cout << endl;
		}
		return;
	}
	if (source_i < source.size())
	{
		s.push(source[source_i++]);
		operations[op_i++] = PUSH;
		solve(source_i, dest_i, op_i);
		source_i--, op_i--;
		s.pop();
	}
	if (!s.empty())
	{
		temp = s.top();
		result[dest_i++] = temp;
		s.pop();
		operations[op_i++] = POP;
		solve(source_i, dest_i, op_i);
		dest_i--, op_i--;
		s.push(temp);
	}
}

Question::Question()
{
	operations = NULL;
	success = false;
}

Question::~Question()
{
	if (operations)
		delete [] operations;
}

int main()
{
	Question question;
	question.input();
	question.solve();
	if (!question.success)
		cout << "输入错误!" << endl;
	return 0;
}

 

你可能感兴趣的:(C++算法和类)