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

本文介绍两种高效的算法来判断一个字符串是否包含另一个字符串的所有字符。通过使用轮询方法和哈希表,文章提供了C语言实现代码,并对比了这两种方法的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

题目:假设这有一个各种字母组成的字符串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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值