ALGO-18 单词接龙

ALGO-18 单词接龙

题目

资源限制

内存限制:256.0MB C/C++时间限制:1.0s Java 时间限制:3.0s Python 时间限制:5.0s

问题描述

单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast 和 astonish,如果接成一条龙则变为 beastonish,另外相邻的两部分不能存在包含关系,例如 at 和 atide 间不能相连。

输入格式

输入的第一行为一个单独的整数 n (n<=20)表示单词数,以下 n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.

输出格式

只需输出以此字母开头的最长的“龙”的长度

样例输入

5
at
touch
cheat
choose
tact
a

样例输出

23

样例说明

连成的“龙”为 atoucheatactactouchoose

代码


import java.util.Scanner;

public class ALGO_18 {
    static String[] words;
    static int[] times;
    static int max_len = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        words = new String[n];
        for (int i = 0; i < n; i++) {
            words[i] = sc.next();
        }
        String head = sc.next();
        sc.close();
        times = new int[n];
        splice(0, head);
        System.out.println(max_len);
    }

    /**
     * 用dfs找到最大的长度
     * @param {int} lap重叠的部分
     * @param {String} head头部词,并没有直接删除重复字符
     */
    private static void splice(int lap, String head) {
        max_len = Math.max(max_len, head.length() - lap);
        for (int i = 0; i < words.length; i++) {
            int index = match(head, words[i]);
            if (index == 0 || times[i] == 2)
                continue;
            times[i]++;
            splice(lap + index, head + words[i]);
            times[i]--;
        }
    }

    /**
     * 双层循环找到两个字符串的匹配位数
     * @param {String} last
     * @param {String} next
     * @return 匹配的位数
     */
    private static int match(String last, String next) {
        for (int i = last.length() - 1; i >= 0; i--) {
            if (last.charAt(i) == next.charAt(0)) {
                int l = i;
                for (int j = 0; j < next.length(); j++) {
                    if (l == last.length())
                        return l - i;
                    if (last.charAt(l) == next.charAt(j))
                        l++;
                    else
                        break;
                }
            }
        }
        return 0;
    }
}

posted @ 2022-04-02 14:18  morning-start  阅读(25)  评论(0编辑  收藏  举报