问题描述:两个字符串,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;
}