Reputation: 11
There are a number of genes in a chromosome and your bioinformatic friend wants to check if a particular chromosome has a series of genes or not. The sequence in which genes occur is important. You want to help your friend in this matter. He gives you n chromosomes and a series of genes he wants to check. Help him identify whether these genes are present in the chromosome in the given order.
Because you are not a biology student, he’s made things easier for you. He represents genes by a letter, number or special character present in ASCII. Spaces do NOT represent a gene.
Example
If the chromosome is abdfgc
, and the genes he’s querying for is abc
, these are present (in the correct order) in the chromosome (marked in bold).
a*b*dfg*c*
. However if the query is bca
, this is not present in the correct order in the chromosome.
Input
The first line of input consists of an integer n
which is the number of test cases.
Each test case consists of two lines of input:
The output for that chromosome-gene pair should be “YES” if the genes, taken in order, are contained in the chromosome and “NO” otherwise. The output should have n lines containing YES/NO.
Constraints
1 <= n <= 10000
1 <= |chromosome| <100
1 <= |gene| < |chromosome|
Sample Input
4
12sd78f
sf
12345efd
1e3d
ijkfgds
jkf
1111456
116
Sample Output
YES
NO
YES
YES
Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class solution {
private static String checkGem(String ch, String gem) {
int prevIndex = 0;
for(int n=0; n < gem.length(); n++) {
if(ch.indexOf(gem.charAt(n), prevIndex)==-1) {
return "NO";
}
else {
prevIndex = ch.indexOf(gem.charAt(n), prevIndex);
}
}
return "YES";
}
public static void main(String args[]) throws Exception {
//Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String test = br.readLine();
int t = Integer.parseInt(test);
for(int i=0; i<t; i++) {
String ch = br.readLine();
String gem = br.readLine();
ch = ch.replaceAll("\\s","");
gem = gem.replaceAll("\\s","");
String ans = checkGem(ch, gem);
System.out.println(ans);
}
}
}
Upvotes: 0
Views: 120
Reputation: 1897
You have a bug in your code. You can try this test case:
1
a
aaaaa
This one should be "NO", but your code output is "YES".
The problem is that you need to advance prevIndex
it should be:
prevIndex = ch.indexOf(gem.charAt(n), prevIndex) + 1;
Upvotes: 0