Difficulty: Easy
Implement .
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
1 2 3
| Input: haystack = "hello", needle = "ll" Output: 2
|
Example 2:
1 2 3
| Input: haystack = "aaaaa", needle = "bba" Output: -1
|
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s and Java’s .
Solution
Language: Java
双重循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null) { return -1; } int j; for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { for (j = 0; j < needle.length(); j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == needle.length()) { return i; } } return -1; } }
|
Robin Carp算法
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 33
| class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null || haystack.length() < needle.length()) { return -1; } if (needle.length() == 0) { return 0; } int len = needle.length(); int MAX = 1000000; int MOD = 31; int target = 0; int cur = 0; int HIGH = 1; for (int i = 0; i < len; i++) { target = ((target * 31) % MOD + needle.charAt(i)) % MOD; HIGH = (HIGH * 31) % MOD; } for (int i = 0; i < haystack.length(); i++) { cur = ((cur * 31) % MOD + haystack.charAt(i)) % MOD; if (i < len - 1) { continue; } if (cur == target && haystack.substring(i - len + 1, i + 1).equals(needle)) { return i - len + 1; } cur = (cur - (haystack.charAt(i - len + 1) * HIGH) % MOD) % MOD; } return -1; } }
|