题目:
给定n个单词的单词表,给定m个查询单词,对于每一次询问,找出所查询的单词是单词表中多少个单词的前缀。
输入:1
5 3
aaaaaa
aaabbb
ababab
dddd
dddd
aaaa
aaa
ax
输出:Case #1:
1
2
0
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class ZifuchuanTest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc = new Scanner(System.in);
System.out.println("输入单词表个数: ");
int n = sc.nextInt();
String[] wordList = new String[n];
for(int i=0;i<wordList.length;i++)
{
System.out.println("请输入一个单词:");
wordList[i] = sc.next();
}
System.out.println("输入查询单词的个数:");
int m = sc.nextInt();
String[] wordQuery = new String[m];
for(int i=0;i<wordQuery.length;i++)
{
System.out.println("请输入一个查询单词:");
wordQuery[i]=sc.next();
}
findCount(wordList, wordQuery);
}
//比较是否是前缀的函数
public static boolean check(String a,String b)
{
boolean t =false;
if(b.length()<=a.length())
{
int count = 0;
if(b.charAt(0)==a.charAt(0))
{
for(int i=0;i<b.length();i++)
{
if(b.charAt(i)==a.charAt(i))
{
count++;
}
}
}
if(count==b.length())
{
t=true;
}
}
return t;
}
//找出单词表中的单词有该前缀的次数
public static void findCount(String []wordList,String []wordQuery)
{
for(int i=0;i<wordQuery.length;i++)
{
int n = 0;
for(int j=0;j<wordList.length;j++)
{
if(check(wordList[j], wordQuery[i]))
{
n++;
}
}
System.out.println(wordQuery[i]+"为前缀的单词的出现次数:"+n);
}
}
}