Implement strStr().this
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Brute Forcecode
Time Complexity
O(N^2)
Space Complexity
O(1)it
When haystack and needle both has 0 length, it is valid, so we need to check from length 0. We only need to check the haystack length - the needle length, because if it is bigger than this length, it won't success.im
public int strStr(String haystack, String needle) { //corner case if(haystack == null || needle == null) return -1; int hlen = haystack.length(), nlen = needle.length(); int start = 0; while(start <= hlen - nlen){ int i1 = start, i2 = 0; while(i2 < nlen && haystack.charAt(i1) == needle.charAt(i2)){ i1++; i2++; } if(i2 == nlen) return start; start++; } return -1; }
""
"a"
expected answer -1
""""
expected answer 0while