Skip to content

Instantly share code, notes, and snippets.

@AnjaliManhas
Created May 7, 2020 12:28
Show Gist options
  • Save AnjaliManhas/21d3b88503b00a7c1a1c974cf1321c37 to your computer and use it in GitHub Desktop.
Save AnjaliManhas/21d3b88503b00a7c1a1c974cf1321c37 to your computer and use it in GitHub Desktop.
Implement strStr()- Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution{
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null)
return -1;
else if(needle.equals(""))
return 0;
else if(haystack.length() == needle.length()) {
if(haystack.equals(needle))
return 0;
else
return -1;
}
for(int i = 0; i < haystack.length() - needle.length() + 1; i++) {
if(haystack.charAt(i) == needle.charAt(0)
&& haystack.substring(i, i+needle.length()).equals(needle))
return i;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment