Created
May 7, 2020 12:28
-
-
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.
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
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