This is a problem in CodeEval, moderate level. The problem is very easy for this level. But I am not able to get more than 60 points for any solution I submit. (Moderate levels highest score is 65 and they take speed and memory into consideration.)
The problem statement is:
There are two strings: A and B. Print 1 if string B occurs at the end of string A. Otherwise, print 0.
Input
- Hello World,World
- Hello CodeEval,CodeEval
- San Francisco,San Jose
Output
- 1
- 1
- 0
import java.io.*;
public class Main {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
String[] words;
while ((line = buffer.readLine()) != null) {
System.out.println(trailingStrings(line));
}
}
public static int trailingStrings(String line) {
int indexOfComma = line.indexOf(",");
int secondStringLength = line.length()-indexOfComma-1;
int firstStringLength = indexOfComma;
if(firstStringLength < secondStringLength) {
return 0;
}
int i = indexOfComma+1;
int j = indexOfComma - secondStringLength;
while(j<indexOfComma) {
if(line.charAt(j) != line.charAt(i)) {
return 0;
}
j++; i++;
}
return 1;
}
}
- Memory Usage: 4784128 (bytes)
- Speed: 644 ms
If I instead split the line with "," and get the words and use String.endsWith()
, I am getting better memory usage. This surprises me because in my first solution I am not creating new String objects, I just use one String
.
import java.io.*;
public class Main {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
String[] words;
while ((line = buffer.readLine()) != null) {
words = line.split(",");
String s1 = words[0];
String s2 = words[1];
if(s1.endsWith(s2)){
System.out.println("1");
} else {
System.out.println("0");
}
}
}
}
- Memory Usage: 413696 (bytes)
- Speed: 1047 ms
Why is my first solution taking up so much memory? Is it because of the int declarations? If I remove int
declarations and use the values directly, memory usage reduced by half to 2412544 bytes but still way higher compared to second solution.
return "0"
andreturn "1"
? I bet whatever java uses to convert int to String is using some memory. \$\endgroup\$