問:有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
^^?我如何使用它在我的問題。謝謝! :)