两个字符串 char* a, char* b,输出b在a中的位置次序

void output_postion(const char* a, const char* b);
如:a = "abdbcc"      b = "abc"
       b 在  a  中的位置次序为
                014
                015
                034
                035 

这个问题和八皇后问题类似,需要用到回溯方法。当检测完字符串b中的c字符时要回溯到上一个状态再继续寻找匹配的位置。


 

#include <iostream>
#include <string>
#include <list>

using namespace std;

/*回溯函数,递归寻找匹配的位置*/
void abstring(string& a, int ai, string& b, int bi, list<int> l)
{
	/*如果字符串b已经遍历结束,则打印list链表内的数值*/
	if( bi == b.length() )
	{
		for( list<int>::iterator it = l.begin(); it != l.end(); ++it )
		{
			cout<<*it;
		}
		cout<<endl;
	}
	else
	{
		/* 遍历字符串a,寻找与字符串b匹配的元素位置 */
		for( int i=ai; i < a.length(); ++i )
		{
			/*找到匹配的字符*/
			if( a[i] == b[bi] )
			{
				/* 将字符的位置加入链表 */
				l.push_back(i);

				/* 继续寻找下一个匹配字符的位置 */
				abstring( a, i+1, b, bi+1, l );

				/* 将链表最后一个元素弹出,回溯到上一个状态 */
				l.pop_back();
			}
		}
		
	}
}

void output_postion(const char* a, const char* b)
{
	string as = a;
	string bs = b;
	list<int> l;

	abstring(as, 0, bs, 0, l);

}

int main()
{
	output_postion("abdbcabc", "abc");

	return 0;
}


 

你可能感兴趣的:(两个字符串 char* a, char* b,输出b在a中的位置次序)