字符串包含问题

问题描述:两个字符串,str1 = “abcde”, str2 = “cba”; 那么str2中的所有字符都在str1中出现,那么就是包含关系,否则为非包含关系。
以下为代码:

#include <iostream>
#include <cstdlib>
#include <cstring>

const int N = 1024;

const int M = 256;

///

int get_index(char c)
{
    int ind = c - 0;
    return ind;
}

bool string_contain(char *line1, char *line2)
{
    if (line2 == NULL)
        return true;
    if (line1 == NULL && line2 != NULL)
        return false;
    int len1 = strlen(line1);
    int len2 = strlen(line2);
    bool key_line1[M];
    memset(key_line1, 0, sizeof(bool)*M);
    int i = 0;
    int ind = -1;
    for (i = 0; i < len1; i++)
    {
        ind = get_index(line1[i]);
        key_line1[ind] = true;        
    }
    for (i = 0; i < len2; i++)
    {
        ind = get_index(line2[i]);
        if (key_line1[ind] == true)
            continue;
        else
            return false;
    }
    return true;
}


bool string_contain_v2(char *line1, char *line2)
{
    if (line2 == NULL)
        return true;
    if (line1 == NULL && line2 != NULL)
        return false;
    int len1 = strlen(line1);
    int len2 = strlen(line2);
    int hash = 0;
    int i = 0;
    for (i = 0; i < len1; i++)
        hash = hash | (1 << (line1[i] - 'a'));
    for (i = 0; i < len2; i++)
    {
        if (hash & (1 << (line2[i] - 'a')))
            continue;
        else
            return false;
    }
    return true;
}

int main(int argc, char *argv[])
{
    char line1[N] = "helloworld";
    char line2[N] = "orel";
    std::cout << "string1, string2: " << line1 << " " << line2 << std::endl;
    bool flag = string_contain_v2(line1, line2);
    if (flag == true)
        std::cout << "string in" << std::endl;
    else
        std::cout << "string not in" << std::endl;
    std::cout << std::endl;
    std::cout << "sizeof int: " << sizeof(int) << std::endl;
    std::cout << "sizeof long: " << sizeof(long) << std::endl;
    std::cout << "sizeof long long: " << sizeof(long long) << std::endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值