Last active
July 30, 2020 12:16
-
-
Save dvt32/6b9653c49c1495b35a976d53ed7a23f7 to your computer and use it in GitHub Desktop.
ALGORITHMO #19 - Naive String Search Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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