H面试程序(10): 字符串包含问题

题目描述:判断第二个字符串中的元素是否都能在第一个字符串中找到:

注意:和字符串的字串的问题有所区别,如第一个字符串为  abcdefg,第二个字符串为 aaabc,第二个字串还是包含于第一个字符串

方法1:将str2中的每一个字符取出,逐一和字符串str1中的字符进行比较
#include <stdio.h>

int WhetherInclude(char*  str1, char * str2)
{
    int ia; 
	int ib = 0;
	

	while(str2[ib] !='') //遍历str2
	{   
		ia = 0;
		while(str1[ia]!='')  //遍历str1
		{   
			if(str1[ia] == str2[ib])
		    	break;
			else
				ia++;
			
		}

		if(str1[ia] == '') //如果经过前面的一次遍历在str1中还是没有找到相同的字符就返回false
			return 0;
		  
		ib++; //增量 来控制外循环      

		 if(str2[ib] == '') //如果查到str2的最后一个字符都没问题的话
            return 1;
		 
	}
}
int main()
{
	char str1[] ="abcdefg";
	char str2[] ="adgc";

	int a = WhetherInclude(str1, str2); //1代表str1包含str2;
	printf("%d
",a);
	return 0;

}


 

方法2,使用hash数组

#include <stdio.h>
#include<malloc.h>
#include<memory.h>
#include<assert.h>

int WhetherInclude(char*  str1, char * str2)  //只能判断str2的字母是不是都在str1中,和子串的问题不一样
{
   char * phash = (char *)malloc(256*sizeof(char)); //进行一些初始化的工作
   assert(phash);
   memset(phash, 0, 256);


   int i = 0;
   while(str1[i-1] != '')    //将str1在phash数组中映射一遍
   {
	   phash[str1[i-1]] = 1;
       i++;
   }


   int j = 0;
   while(str2[j-1] != '') //将str2和str映射后的表再映射一遍,发现为0的位即不包含
   {
	   if(phash[str2[j-1]] == 0)
		   return 0;
	   j++;
   }
   return 1;
		 
	
}
int main()
{
	char str1[] ="abcdefg";   
	char str2[] ="aaagc";

	int a = WhetherInclude(str1, str2); //1代表str1包含str2;
	if(a = 0)
		printf("不是所有字符串str2中的字符在str1中都能找到!!!
");
	else
	    printf("所有字符串str2中的字符在str1中都能找到
");
	
	return 0;

}


原文地址:https://www.cnblogs.com/pangblog/p/3263261.html