问:有N个字符串。每个字符串的长度不超过20个字符。还有Q查询。对于每个查询,都会给出一个字符串,并且您需要查明此字符串以前发生过多少次。执行稀疏阵列
采样输入
[主要列表]
ABA
巴巴
ABA
xzxb
[查询]
ABA
xzxb
AB
样本输出
(ABA出现两次出现在主列表)
(xzxb在主列表中出现一次)
(AB没有出现在主力名单)
我的代码
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); // CONTAINS N number of String
String word[] = new String[N]; //Sets N as size of an array
for(int i = 0; i < N; i++){
word[i] = scan.nextLine();//Stores a word in every index of an array
}
scan.nextLine(); //Flush index??(need help?!)
int Q = scan.nextInt(); // Stores number of query
String searchWord[] = new String[Q];//integer for size of query array
for(int i = 0; i <Q; i++){
searchWord[i] = scan.nextLine(); // stores query array for comparison
}
int counter = 0; // initializing counter
for(int i=0; i <Q; i++){//Take a query word and check if it exists in word[]
for(int j =0; j <N; j++){//searches for the query word in main List
if(word[j] == searchWord[i]){// if it exists counter value adds +1
counter++;
}
}
System.out.println(counter); //print counter
counter = 0; // reset counter
}
}
}
首先代码确实不是工作,虽然逻辑看起来是正确的(我猜的)。也有人给我解释一下为什么我们需要消耗换行符左在做
input.nextLine();
源:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
问题:https://www.hackerrank.com/challenges/sparse-arrays
^^?我如何使用它在我的问题。谢谢! :)