Q: There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.
Sample Input
[Main List]
4
aba
baba
aba
xzxb
[Query]
3
aba
xzxb
ab
Sample Output
2 (aba appears twice appear in the main list)
1 (xzxb appears once in the main list)
0 (ab doesn't appear in the main list)
My Code
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
}
}
}
First of all the code does NOT work although the logic is seemingly correct (i guess). Also can someone explain me why we need to consume newline left-over by doing
input.nextLine();
src: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Question : https://www.hackerrank.com/challenges/sparse-arrays
^^ And how do I use it in my question. Thank you! :)