快速匹配兄弟字符串

题目:如果两个字符串的字符一样,但是顺序不一样,被认为是兄弟字符串,问如何快速匹配兄弟字符串(如,bad和adb就是兄弟字符串)。

解法:设置一个int型的二维数组count[2][126](126是为了与ASCII码表中常用字符数统一,便于累加处理),分别统计两个字符串中字符出现个数,然后比较count[0]和count[1],看是否一致。

#include <iostream>
#include <string>

using namespace std;

bool check(string _tocompare1, string _tocompare2)
{
	if(_tocompare1.length != _tocompare2.length)
	{
		return false;
	}
	const char *cmp1ptr = _tocompare1.c_str();
	const char *cmp2ptr = _tocompare2.c_str();
	int count[2][126];
	memset(count, 0, sizeof(int) * 2 * 126);
	while(*cmp1ptr != '\0')
	{
		count[0][*cmp1ptr++]++;
		count[1][*cmp2ptr++]++;
	}
	for(int cmp = 0; cmp < 126; ++cmp)
	{
		if(count[0][cmp] != count[1][cmp])
		{
			return false;
		}
	}
	return true;
}

int main()
{
	bool result = check("aabb67^", "^76baba");
	string resultstr;
	cout<<(result ? (resultstr = "the same") : (resultstr = "not the same"))<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/skeleton703/article/details/8806777
今日推荐