I am trying to implement simple String matching. The algorithm should return 1 if the source String contains the pattern String. I cannot understand why it is returning -1 on the following inputs
String source = "aababba";
String pattern = "abba";
Here is my implementation:
public static int findMatch(String source, String pattern)
{
int j = 0, pos = -1;
boolean matched = false;
if(source.length() < pattern.length())
return -1;
for(int i = 0; i < (source.length() - pattern.length()); i++)
{
if(source.charAt(i) == pattern.charAt(j))
j++;
else
j = 0;
if(j == pattern.length())
{
matched = true;
break;
}
}
if(matched)
return 1;
return -1;
}
EDIT: As many of you suggested, the culprit was the for loop. I should have made it as follows. The rest of the code is the same. Other solutions are also possible as shown in the answers.
for(int i = 0; i <= (source.length() - pattern.length()); i++)
{
if(source.charAt(i+j) == pattern.charAt(j))
{
(source.length() - pattern.length())inforloop?1instead of-1? Is it because source contains the pattern? Or does source just have to contain all of the letters of pattern? Or something else?