数据结构——算法之(011)( 字符串是否包含问题)

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:[email protected]

题目:假设这有一个各种字母组成的字符串A,和另外一个字符串B,字符串里B的字母数相对少一些。什么方法能最快的查出所有小字符串B里的字母在大字符串A里都有?

题目分析:

一、注意字符串B中可能有称呼包含相同字符

解法一、轮训方法

(1)先遍历短的字符串,把每个取出的字符在长字符串中查找

(2)遍历次数(m*n)

解法二、哈希

(1)定义一个数组hash[26],并清0。定义一个不同字符出现次数总和m

(2)遍历短字符串,把找到的字符相应位置置1,m++

(3)遍历长字符串,把找到的字符相应位置置0,m--

(4)最后m等于0,则是包含关系,否则是非包含关系

算法实现:

#include <stdio.h>
#include <string.h>

#ifndef bool
typedef enum
{
	false,
	true,
}bool;
#endif

/*
** method one: loop twice
*/
bool str_in(const char *long_str, const char *short_str)
{
	int j,i;
	int long_len = strlen(long_str);
	int short_len = strlen(short_str);
	for(i=0; i<short_len; ++i)
	{
		for(j=0; j<long_len; j++)
		{
			if(long_str[j] == short_str[i])
				break;
		}
		if(j == long_len)
			return false;
	}
	return true;
}

/*
** method two: hash
*/
bool str_in_1(const char *long_str, const char *short_str)
{
	if(!long_str || !short_str)
		return -1;
	int i,total=0;
	int long_len = strlen(long_str);
	int short_len = strlen(short_str);
	
	int hash[26] = {0};
	int key = 0;
	for(i=0; i<short_len; ++i)
	{
		key = short_str[i] - 'A';
		if(hash[key] == 1)
			continue;
		hash[key] = 1;
		total++;
	}
	
	for(i=0; i<long_len; ++i)
	{
		key = long_str[i] - 'A';
		if(hash[key] == 0)
			continue;
		hash[key] = 0;
		total--;
	}
	
	return (total == 0?true:false);
}
int main(int argc, char *argv[])
{
	printf("--->%d\n", str_in("ABCDEFGHLMNOPQRS", "DCGSRQPO"));
	printf("--->%d\n", str_in("ABCDEFGHLMNOPQRS", "DCCGSRQPO"));
	printf("--->%d\n", str_in("ABCDEFGHLMNOPQRS", "DCCGGSRQPOz"));
	printf("--->%d\n", str_in_1("ABCDEFGHLMNOPQRS", "DCGSRQPO"));
	printf("--->%d\n", str_in_1("ABCDEFGHLMNOPQRS", "DCCGSRQPO"));
	printf("--->%d\n", str_in_1("ABCDEFGHLMNOPQRS", "DCCGGSRQPOz"));
	return 0;
}




你可能感兴趣的:(数据结构——算法之(011)( 字符串是否包含问题))