Find the longest word from the English alphabet

Link: https://www.nowcoder.com/acm/contest/107/B
Source: Niuke.com

Problem description
There is an English practice game that gives you some letters at a time, and then asks you to spell the longest English word from it.
Although williamchen's English is very poor, he now has an English dictionary, and he just needs to find the longest eligible letter in the dictionary.
Now you need to write a program to help him accomplish this task.
Input description:
It contains multiple sets of test data, and the first line of each set of data contains no more than 20 letters, indicating the letters given by the game.
Next is a line with a number N (1 <= N <= 1000)
followed by N lines, each line is a string representing a word in the dictionary, and the word length will not exceed 10.
Output description:
One line is output for each set of data, indicating the longest possible word length. If one word cannot be spelled, output 0.
Example 1
input
masterblodpo
7
boogie
magnolia
punch
blood
master
inherent
phantom
ablderrivala
5
arrival
blade
runner
incendies
sicario
output
6
7

import java.util.HashMap;
import java.util.Scanner;


public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext())
        {
            String str = sc.next();
            int[] chars =getStringChars(str);
            int maxLength =0;
            int n = sc.nextInt();
            for (int i = 0; i < n; i++)
            {
                int[] copyChars = chars.clone();
                String inStr = sc.next();
                int strLength =inStr.length();
                if(strLength >maxLength)
                {
                    if(checkString(copyChars,inStr))
                    {
                        maxLength =strLength;
                    }
                }
            }
            System.out.println(maxLength);
        }
    }

    private static int[] getStringChars(String str)
    {
        int[] chars = new int[256];
        for (int i = 0; i < str.length(); i++)
        {
            chars[str.charAt(i)]++;
        }
        return chars;
    }

    private static boolean checkString(int[] chars,String str)
    {
        for (int i = 0; i < str.length(); i++)
        {
            char c =str.charAt(i);
            chars[c]--;
            if(chars[c] <0) return false;
        }
        return true;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312842&siteId=291194637