實現 strStr() 函數。算法
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。若是不存在,則返回 -1。網絡
示例 1:函數
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:spa
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1code
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/implement-strstr
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。blog
兩種解法。leetcode
第一種:暴力直接求解,時間複雜度是O(n^2)。字符串
第二種:Rabin-Karp算法。get
時間複雜度O(m + n)。string
class Solution { public int strStr(String haystack, String needle) { if(haystack == null || needle == null) return -1; for(int i=0; i < haystack.length() - needle.length() + 1; i++){ int j = 0; for(; j < needle.length(); j++){ if(haystack.charAt(i + j) != needle.charAt(j)) break; } if(j == needle.length()) return i; } return -1; } }
class Solution { static final int BASE = 1000000; public int strStr(String haystack, String needle) { if(haystack == null || needle == null) return -1; if(needle.length() == 0) return 0; int m = needle.length(); //31 ^ m int power = 1; for (int i = 0; i < m; i++) { power = (power * 31) % BASE; } int targetCode = 0; for (int i = 0; i < m; i++) { targetCode = (targetCode * 31 + needle.charAt(i)) % BASE; } int hashCode = 0; for (int i = 0; i < haystack.length(); i++) { hashCode = (hashCode * 31 + haystack.charAt(i)) % BASE; if(i < m - 1){ continue; } //減去開始的數 abcd - a if(i >= m) { hashCode = hashCode - (haystack.charAt(i - m) * power) % BASE; if(hashCode < 0){ hashCode += BASE; } } //雙重校驗 if(hashCode == targetCode){ if(haystack.substring(i - m + 1, i + 1).equals(needle)){ return i - m + 1; } } } return -1; } }