• 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;
    }
  • 相关阅读:
    模拟Spring的Ioc
    Java常见异常总结
    Java编码与乱码问题
    Java正则表达式入门
    观察者模式
    Java内存泄漏问题
    责任链模式
    选择排序(C++/Java实现)
    设计模式学习工厂模式
    Java验证码
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4662634.html
Copyright © 2020-2023  润新知