Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
028. Implement strStr () (easy)
links:
Title: https://oj.leetcode.com/problems/implement-strstr/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Find the position of another string in a string.
Analysis:
This problem is attributed to the easy class because it has n*n of violence.
If the data is strong, it has to midium above.
- (c + +) The Violence O (n^2) is two times for to find
- (c + +) There are a variety of tall algorithms, such as the KMP algorithm, which is classic, concrete implementation see my other blog.
- (Python) can also use hash to do, called rolling hash algorithm (see Wiki and StackOverflow), is the string hash out, by matching string length window to scroll, and then to match. Hash string There are many ways, the letter here seems to be lowercase, there are 26, so 29 to do the cardinality (originally imagined DJB2 algorithm with 33 to do the base, can be directly
((hash << 5) + hash)
quickly, but the int range can only hash 6 letters and rolling when still want to , or 29), the super int range of words with Python will not consider this problem.
Other also have boyer–moore,rabin–karp algorithm, specific oneself to search.
Code:
C + +: Violence
Class Solution {public: int strStr (char *haystack, char *needle) {int hlen = strlen (haystack); int nlen = strlen (needle if (Hlen < Nlen) return-1;for (int i = 0; I <= hlen-nlen; i++) {if (!strncmp (haystack + i, needle, nlen)) return i;} return-1; }};
C + +: KMP
Class Solution {Private:int next[1000100];p ublic: int strStr (char *haystack, char *needle) {int hlen = strlen (Haystac k); int nlen = strlen (needle); int i, j;if (Hlen < Nlen) Return-1;if (Nlen = = 0) return 0;//kmp//get next matching array int *next = new Int (nlen + 1);//Because The string would be a 1 million, so we cannot use ' int *next = new Int (Nlen + 1) ' , it'll exceed the memory in Functioni = 0;j = -1;next[0] = -1;while (i < Nlen) {if (j = =-1 | | needle[i] = = Needle[j ]) {I++;j++;next[i] = j;} Elsej = Next[j];} Matchingi = 0;j = 0;while (i < Hlen) {if (j = =-1 | | haystack[i] = = Needle[j]) {i++;j++;} Elsej = Next[j];if (j = = n Len) return I-nlen;} return-1; }};
Python:
Class solution: # @param haystack, a string # @param needle, a string # @return An integer def strStr (self , haystack, needle): hlen, nlen = Len (haystack), Len (needle) if Nlen = = 0: return 0 if Nlen > Hlen or H Len = = 0: return-1 rolling = lambda x, y:x * + y get_hash = lambda ch:ord (CH)-ord (' a ') Nhash = R Educe (rolling, map (Get_hash, needle)) Hhash = reduce (rolling, map (Get_hash, Haystack[:nlen))) if Nhash = = Hhash: return 0 high_base = * * (nlen-1) for I in range (Nlen, Hlen): Hhash-= Get_hash (haystack[i -Nlen]) * High_base # Remove First in hash code Hhash = Rolling (Hhash, Get_hash (haystack[i)) # Add new if Nhash = = Hhash: return I-nlen + 1 return-1
[Leetcode] 028. Implement strStr () (easy) (C++/python)