[编程之美-10]字符串的包含问题

[题目描述] 给定一长字符串 a 和一段字符串 b 。请问, 如何最快的判断出短字符串 b 中的所有字符是否都在长字符串 a 中。
[Sample Input]
ABCD BAD
ABCD BCE
ABCD AA

[Sample Output]
true
false
true

基本解法:我们遍历字符串b,依次判断b中的每个字符是不是的都在字符串a中。
代码如下:

#include<iostream>
#include<string>
using namespace std; 

bool stringContain(string &a, string &b);

int main()
{
    string a, b;
    while(cin>>a>>b)
    {
        if(stringContain(a, b))
            cout<< "true" << endl;
        else
            cout<< "false" << endl;
    }
    return 0;   
} 

bool stringContain(string &a, string &b)
{
    for(int i = 0; i < b.length(); i ++)
    {
        if(a.find(b[i]) > b.length())
            return false;
    }
    return true;
}

时间复杂度:O(m*n), 空间复杂度:O(1)

高效算法:思考角度,我们都知道ASCII码一共有127个,而题目所说的字符串都是由ASCII码组合而成。首先遍历字符串a,将a中每个字符转化为int类型(作为数组角码)。并开辟数组大小为128的bool类型count数组。count[a[i]] = true.接着去遍历字符串b,依次判断每个字符是否count[b[i]] == true.

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

bool stringContain(string &a, string &b);

int main()
{
    string a, b;
    while(cin>>a>>b)
    {
        if(stringContain(a, b))
            cout<< "true" << endl;
        else
            cout<< "false" << endl;
    }
    return 0;   
} 

bool stringContain(string &a, string &b)
{
    bool count[128];
    memset(count, false, sizeof(count));

    for(int i = 0; i < a.length(); i ++)
    {
        count[a[i]] = true;
    }

    for(int i = 0; i < b.length(); i ++)
    {
        if(count[b[i]] == false)
            return false;
    }
    return true; 
}

时间复杂度:O(m+n), 空间复杂度:128B

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值