java - java代码有什么问题,因为hashmap是根据值的数量存储键
问题描述
输入如下:-
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
而不是得到它如下
是 是 否
否 否 否 是
解决方案
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
推荐阅读
- python - 如何将 Dialogflow 与 Django python 集成并使用 RESTful API?
- android - Social.localUser.Authenticate 回调从未被调用
- angular - cdk virtualscroll with mat-grid-list
- java - 将复杂的“字符串”转换为“布尔”
- xml - 创建表形式学说 orm.xml 文件
- cdi - TransactionImpleManager.suspend 隐式调用
- php - 为什么我的带有分页参数的 WordPress ajax 调用响应总是给我第一页?
- r - 过滤 difftime 在 5 天内的日期
- javascript - 是否在用 jQuery 替换 HTML 时执行任何脚本
- .net - UWP 位置绝对弹出窗口