输入如下:-
2
3 2
piygu ezyfo rzotm
1 piygu
6 tefwz tefwz piygu ezyfo tefwz piygu
4 1
kssdy tjzhy ljzym kegqz
4 kegqz kegqz kegqz vxvyj
第一个输入是测试用例的数量。第二行有两个整数(n & k)。第一个(n)是指单词的数量。第二个整数 (k) 指的是接下来的行数。 然后下一行包含 n 个单词。然后是他们的k线。每行都有一个整数(l),表示同一行中的单词数。问题是根据第一行中的单词在其他行中是否可用来打印是或否。
import java.util.*;
public class ForgottenLanguage {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int k=sc.nextInt();
sc.nextLine();
HashMap<String,String> hashmap=new HashMap<String,String>();
for(int i=0;i<n;i++) {
String a=sc.next();
hashmap.put(a,"NO");
}
sc.nextLine();
while(k-->0) {
int l=sc.nextInt();
for(int i=0;i<l;i++) {
String st=sc.next();
if(hashmap.containsKey(st)) {
hashmap.put(st, "YES");
}
}
for(String s:hashmap.keySet()) {
System.out.print(hashmap.get(s)+" ");
}
}
}
sc.close();
}
}
我已经实现了这段代码。我得到的输出如下
YES NO NO YES YES NO
NO NO YES NO
而不是如下获取它
是 是 否
没有没有没有
答案 0 :(得分:2)
Improvement:
Map<String, String>
在这种情况下很难维护。我用 Map<String, Boolean>
更改它。Correction:
要维护实际顺序,请使用 LinkedHashMap
。 HashMap
类不维护元素的 order
。这就是为什么最后的输出不像预期的那样。Correction:
不要在 System.out
内打印(2nd loop
),而是在 2nd while loop
完成后立即打印数据。您的代码的修改版本:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class ForgottenLanguage {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
sc.nextLine();
Map<String, Boolean> linkedHashmap = new LinkedHashMap<String, Boolean>();
for (int i = 0; i < n; i++) {
String a = sc.next();
linkedHashmap.put(a, false);
}
sc.nextLine();
while (k-- > 0) {
int l = sc.nextInt();
for (int i = 0; i < l; i++) {
String st = sc.next();
if (linkedHashmap.containsKey(st)) {
linkedHashmap.put(st, true);
}
}
//remove printing logic from here
}
for (Map.Entry<String, Boolean> entry : linkedHashmap.entrySet())
{
if(entry.getValue()) {
System.out.print("YES" + " ");
}else {
System.out.print("NO" + " ");
}
}
}
sc.close();
}
}
我的控制台视图(输入-输出):
2
3 2
piygu ezyfo rzotm
1 piygu
6 tefwz tefwz piygu ezyfo tefwz piygu
YES YES NO
4 1
kssdy tjzhy ljzym kegqz
4 kegqz kegqz kegqz vxvyj
NO NO NO YES