Implement strStr()
.
Returns the index of the first occurrence of needle
in haystack
, or -1 if needle
is not part of haystack
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
public class StrStr { public int strStr(String haystack, String needle) { if (needle == null || needle.length() == 0) { return 0; } if (haystack == null || haystack.length() == 0) { return -1; } for (int i = 0; i < haystack.length(); i++) { char c = haystack.charAt(i); if (haystack.length() - i + 1 < needle.length()) { return -1; } if (c == needle.charAt(0)) { int j = 0; int k = i; for (; j < needle.length() && k < haystack.length(); j++, k++) { if (needle.charAt(j) != haystack.charAt(k)) { break; } } if (j == needle.length()) { return (k - j); } } } return -1; } }
|