【和LULY大神学算法】字符串是否包含问题


学习资源链接http://blog.csdn.net/v_july_v/article/details/6347454

本文实现的是2.2数组实现法

改进之处是数组不是布尔型,而是int 型。当短串中字符出现一次,对应位置加一。初值都为0.这样可实现一个字符多次出现的情况。


源代码:

// artofcoding.cpp : Defines the entry point for the console application.
//

/*
程序员编程艺术:第二章、字符串是否包含问题
  题目描述:
假设这有一个各种字母组成的字符串A,和另外一个字符串B,字符串里B的字母数相对少一些。
什么方法能最快的查出所有小字符串B里的字母在大字符串A里都有?


比如,如果是下面两个字符串:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPO
答案是true,所有在string2里的字母string1也都有。
  
如果是下面两个字符串:  
String 1: ABCDEFGHLMNOPQRS   
String 2: DCGSRQPZ  
答案是false,因为第二个字符串里的Z字母不在第一个字符串里。

*/


#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

void al_array( int *array, string s_string){  //为数组赋值
for( int i=0; i<26; i++)
array[i] = 0;


int len= s_string.length();
for( i=0; i< len; i++)
array[ s_string[i] -'a' ] ++;
};


void check( int *array, string l_string){ //长串论询
int len=l_string.length();
for( int j=0; j< len; j++){
if(  array[ l_string[j]-'a' ] !=0 )  //appears in the short string
array[ l_string[j]-'a' ]--;

}


};


bool judge( int *array){ //判断结果
for( int m=0; m<26; m++)
if( array[m] != 0)
return false;




return true;


};
int main(int argc, char* argv[])
{
string longstring, shortstring;
cout << "input the long string:" << endl;
cin >> longstring;
cout << "input the short string:" << endl;
cin >> shortstring;


int array[26];


al_array(array, shortstring);
check(array, longstring);

bool result = judge(array);


if(result)
cout << "the short string is contained by the long one!" << endl;
else
cout << "the short string is not contained by the long one!" << endl;



return 0;
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值