文字列マッチングアルゴリズム実装(両方の文字列に含まれる文字と個数は同じ)

539 ワード

2つの文字列に含まれる文字と個数が同じであると仮定して、abcdaとadabcのような2つの文字列マッチングと呼びます.出現する文字の個数は同じで、順序が異なるだけなので、この2つの文字列は一致します.
int match( const unsigned char *s1, const unsigned  char *s2 )
{
	int  a[256] = {0}; //a[97]     ‘a'     
	int i = 0;

	while( *s1 != '\0' )
	{
		a[*s1]++;  //   *s1   
		s1++;
	}
	while( *s2 != '\0' )
	{
		a[*s2]--; //   1  ,       ,   0
		s2++;
	}	
	// a[i]   ,  s1 s2    a[i]  ASCII  i   。     。
	for(i=0; i<=255; i++)
	{
		if( a[i] != 0 )
		{
			return 0; //   
		}
	}
	return 1;  //  
}