acm-单词拼接

单词拼接
时间限制:3000 ms | 内存限制:65535 KB
难度:5

描述

给你一些单词,请你判断能否把它们首尾串起来串成一串。

前一个单词的结尾应该与下一个单词的道字母相同。

如

aloha

dog

arachnid

gopher

tiger

rat



可以拼接成:aloha.arachnid.dog.gopher.rat.tiger

输入
第一行是一个整数N(0

import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

public class ConnectWord {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        for (int i = 0; i < num; i++) {
            int wordCount = scanner.nextInt();
            String[] words = new String[wordCount];
            for (int j = 0; j < wordCount; j++) {
                words[j] = scanner.next();
            }

            Arrays.sort(words);

            StringBuilder sb = new StringBuilder();
            String lastWord = "";
            for (int k = 0; k < wordCount - 1; k++) {
                String wordOne = words[k];
                char endChar = wordOne.charAt(wordOne.length() - 1);
                String wordTwo = words[k + 1];
                char firstChar = wordTwo.charAt(0);
                if (!Objects.equals(endChar, firstChar)) {
                    break;
                }
                if (!wordOne.equals(lastWord)) {
                    sb.append(wordOne);
                }
                sb.append(".").append(wordTwo);
                lastWord = wordTwo;
            }

            if (lastWord.equals(words[wordCount - 1])) {
                System.out.println(sb.toString());
            } else {
                System.out.println("***");
            }

        }
    }
}

你可能感兴趣的:(acm,java)