hdoj 1247 Hat’s Words(字典树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

思路分析:题目要求找出在输入字符串中的满足要求(该字符串由输入的字符串中的两个字符串拼接而成)的字符串。

对于长度为LEN的字符串,其可能由LEN种可能的拼接可能;现在问题转化为查找能够拼接成该字符串的可能的两个字符串是否都在

输入的字符串中,使用字典树可以实现快速的字符串查找,算法复杂度为O(N*M),N为输入字符串的个数,M为字符串长度。

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int LEN = 100;
const int MAX_N = 50000 + 10;
const int KIND = 26;
char str[MAX_N][LEN];

struct Node {
    Node *next[KIND];
    bool end;
    Node()
    {
        memset(next, 0, sizeof(next));
        end = false;
    }
};

void Insert(Node *root, char *str)
{
    int i = 0, k = 0;
    Node *p = root;

    while (str[i]) {
        k = str[i] - 'a';
        if (!p->next[k])
            p->next[k] = new Node();
        p = p->next[k];
        ++i;
    }
    p->end = true;
}

bool Find(Node *root, char *str)
{
    int i = 0, k = 0;
    Node *p = root;

    while (str[i]) {
        k = str[i] - 'a';
        p = p->next[k];
        if (!p)
            return false;
        ++i;
    }
    return p->end;
}

int main()
{
    int count = 0;
    Node *root = new Node();
    char sub_str1[LEN], sub_str2[LEN];

    while (scanf("%s", str[count]) != EOF)
        Insert(root, str[count++]);
    for (int i = 0; i < count; ++i) {
        int len = strlen(str[i]);
        for (int j = 1; j < len; ++j) {
            strncpy(sub_str1, str[i], j);
            sub_str1[j] = '';
            strncpy(sub_str2, str[i] + j, len - j);
            sub_str2[len - j] = '';
            if (Find(root, sub_str1) && Find(root, sub_str2)) {
                printf("%s
", str[i]);
                break;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tallisHe/p/4662634.html