代码改变世界

字符串包含判断

2013-05-30 13:28  夜与周公  阅读(372)  评论(0编辑  收藏  举报

  本节总结编程的艺术(CSDN)字符串包含操作。

  算法描述:假设有两个由字母组合的字符串A和字符串B,字符串A的长度要大于字符串B的长度。算法如何判断出现在字符串B中的字母也出现在字符串A呢?

  算法举例:StringA = "ABCDEFG", 若StringB = "DCEFG",则StringA与StringB之间算法判断是true;若StringB = "DCEFM"。 而StringA与StringC之间算法判读是false。

  我们首先可以想到的办法是:遍历StringB,对于B中每一个字母,遍历字符串A,判断当前字母是出现在字符A中。算法的时间复杂度O(n*m),空间复杂度O(1)。

#include "stdafx.h"
using namespace std;

bool compare_string(string a, string b)
{
    bool is_match = false;
    for (int i = 0; i != b.length(); i++)
    {
        int j = 0;
        for (; j != a.length(); j++)
        {
            if (b[i] == a[j])
                break;
        }
        if (j == a.length())
            return is_match;
    }
    is_match = true;
    return is_match;
}

int _tmain(int argc, _TCHAR* argv[])
{
    string a = "abcedfg";
    string b = "ceab";
    bool is_match = compare_string(a,b);
    if (is_match)
        cout<<"Match!";
    else
        cout<<"Not Match!";
    system("pause");
    return 0;
}

  

  我们进一步观察语料不难发现,字符串仅出现字母,因此字符串的“规模”就被限定了(字符串中只能出现26个大写字母与小写字母),因此我们可以使用哈希表方法,先将字符串A映射到哈希表中,然后对于字符B中的每个字符,直接查表判断是否存在。算法的时间复杂度O(n),空间复杂度O(K),k等于26*2。

#include "stdafx.h"
using namespace std;
bool compare_string(string a, string b)
{
    bool is_match = true;
    const int table_size = 26;
    int hash_table[table_size*2] = {0};
    //将字符串a映射到哈希表中
    for (int i=0; i!=a.length(); i++)
    {
        int index = a[i]>'z' ? a[i]-'A'+table_size : a[i]-'a';
        hash_table[index] = 1;
    }
    //对于字符串b中的每个字符串,查找哈希表判断是否在a中是否存在
    for (int i=0; i!=b.length();i++)
    {
        int index = b[i]>'z' ? b[i]-'A'+table_size : b[i]-'a';
        if (!hash_table[index])
        {
            is_match = false;
            break;
        }
    }
    return is_match;

}

int _tmain(int argc, _TCHAR* argv[])
{
    string a = "Abcedfg";
    string b = "cebA";
    bool is_match = compare_string(a,b);
    if (is_match)
        cout<<"Match!";
    else
        cout<<"Not Match!";
    system("pause");
    return 0;
}