This is the challenge I tried in Codefights: Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview. Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1. How can I make it faster? Thanks in advance. Here's my code, which is still slow for larger input cases(string of around 10^6 characters):
int findFirstSubstringOccurrence(String s, String x) {
int j=0;
for (int i=0; i<=(s.length()-x.length()); i++) {
j=0;
while ((j<x.length()) && s.charAt(i+j)==x.charAt(j)){
j++;
}
if (j == x.length())
return i;
if(s.charAt(i+j)!=s.charAt(i))
i += j;
}
return -1;
}