I implemented one program in Java, which surprising took 177M memory for particular test-cases (I do not have since program are tested by one website).
The problem was to find out all the characters of string S2, which are present in string S1. And there are N such cases.
public static void main(String[] args) throws Exception {
BufferedReader bin = new BufferedReader (new InputStreamReader (System.in));
String jewel, stone;
int t = Integer.parseInt (bin.readLine());
int count;
int i;
while (t-->0) {
count = 0;
jewel = bin.readLine();
stone = bin.readLine();
for (i=0; i<stone.length(); i++) {
if (jewel.indexOf(stone.charAt(i)) !=-1) {
count++;
}
}
System.out.println(count);
}
}
I also do not understand, how it is taking 177M of ram. Even if they are testing a huge file then also only 2 strings are there. However code was perfectly working and test-cases passed.
Since java program was taking huge amount of memory, so I planned to write a C version of same program. which is following:
int main ()
{
char * pch;
char jewel[100], stone[100];
int n;
scanf("%d",&n);
int len;
int tp;
int count = 0;
getchar(); // remove trailing '\n'
while (n-->0) {
gets(jewel);
pch = gets(stone);
count = 0;
while(*pch ) {
if (strchr(jewel, *pch)) {
count++;
}
pch++;
}
printf("%d\n", count);
}
return 0;
}
On few existing cases, it is working. Program seems to be correct too. But I am unable to understand why it is passing all test cases correctly.
All the strings buffer are long enough to hold the incoming strings, which are separated by new lines.
EDIT: Changing ""+stone.charAt(i))
to stone.charAt(i))
did not help and took same amount of memory. Also why this C code is not able to pass all the test cases ?