Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dvt32/6b9653c49c1495b35a976d53ed7a23f7 to your computer and use it in GitHub Desktop.
Save dvt32/6b9653c49c1495b35a976d53ed7a23f7 to your computer and use it in GitHub Desktop.
ALGORITHMO #19 - Naive String Search Implementation
public class StringSearch {
public static int getSubstringStartIndex(String text, String pattern) {
int n = text.length();
int m = pattern.length();
for (int startIndex = 0; startIndex <= ( n - m ); ++startIndex) {
int i = 0;
for (i = 0; i < m; ++i) {
if (pattern.charAt(i) != text.charAt(startIndex + i)) {
break;
}
}
if (i == m) { // if all pairs of characters have matched
return startIndex;
}
}
return -1; // substring not found in string
}
public static void main(String[] args) {
int substringStartIndex = getSubstringStartIndex("NOAH NOTICED", "NOT");
System.out.println(substringStartIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment