
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
1 2
|
Input: haystack = "hello", needle = "ll" Output: 2
|
Example 2:
1 2
|
Input: haystack = "aaaaa", needle = "bba" Output: -1
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class { 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() - needle.length() + 1; i++) { if (haystack.charAt(i) == needle.charAt(0)) { if (needle.equals(haystack.substring(i, i + needle.length()))) { System.out.println(haystack.substring(i, i + needle.length())); return i; } } } return -1; } }
|
近期评论