Ji You attended an interview with Alibaba intern two days ago and asked a question about the string-based substring search. The implementation method is nothing more than a two-layer loop, but there is a ready-made implementation in Java, so I went to check the source code to see how the Java language achieves this, and found that it is similar.
In the java. lang Package, the string class has several indexof () functions. I am looking for the specific implementation of indexof (string Str ).
public int indexOf(String str) {return indexOf(str, 0);}
Then F3 continues searching,
public int indexOf(String str, int fromIndex) {return indexOf(value, offset, count, str.value, str.offset, str.count,fromIndex);}
This call should be the implementation of the algorithm. Continue F3
/** * Code shared by String and StringBuffer to do searches. The source is the * character array being searched, and the target is the string being * searched for. * * @param source * the characters being searched. * @param sourceOffset * offset of the source string. * @param sourceCount * count of the source string. * @param target * the characters being searched for. * @param targetOffset * offset of the target string. * @param targetCount * count of the target string. * @param fromIndex * the index to begin searching from. */static int indexOf(char[] source, int sourceOffset, int sourceCount,char[] target, int targetOffset, int targetCount, int fromIndex) {if (fromIndex >= sourceCount) {return (targetCount == 0 ? sourceCount : -1);}if (fromIndex < 0) {fromIndex = 0;}if (targetCount == 0) {return fromIndex;}char first = target[targetOffset];int max = sourceOffset + (sourceCount - targetCount);for (int i = sourceOffset + fromIndex; i <= max; i++) {/* Look for first character. */if (source[i] != first) {while (++i <= max && source[i] != first);}/* Found first character, now look at the rest of v2 */if (i <= max) {int j = i + 1;int end = j + targetCount - 1;for (int k = targetOffset + 1; j < end&& source[j] == target[k]; j++, k++);if (j == end) {/* Found whole string. */return i - sourceOffset;}}}return -1;}
Note that this function is a static function, which is a tool common to string and stringbuffer. The specific algorithm principle code is obvious.
I have consulted some materials. Currently, there are several methods to search for substrings,
KMP algorithm, BM algorithm, and Sunday Algorithm
The order of simplicity and efficiency is as follows:
Sunday> BM> KMP
The core idea of the Sunday algorithm is as follows (from Baidu encyclopedia ):
The concept of the Sunday algorithm that surpasses BF, KMP, and BM in string mode matching is as follows: the Sunday algorithm is a faster algorithm proposed by Daniel M. Sunday in 1990 than the BM algorithm. The core idea is: During the matching process, the pattern string is not required to be compared from left to right or from right to left. When a mismatch is found, the algorithm can skip as many characters as possible to perform the next matching, thus improving the matching efficiency. Assume that s [I] ≈ T [J], 1 ≤ I ≤ n, 1 ≤ j ≤ m in case of mismatch. At this time, the matched part is U, and the length of the string U is assumed to be L. 1. Obviously, s [L + I + 1] must participate in the next round of matching, and t [m] should at least move to this position (that is, the mode string T should move at least one character to the right ).
Figure 1 Sunday algorithm MismatchThere are two cases: (1) s [L + I + 1] does not appear in the mode string T. At this time, the mode string T [0] is moved to the character position after s [T + I + 1. 2.
Figure 2 1st cases of Sunday algorithm moving(2) S [L + I + 1] appears in the mode string. Here s [L + I + 1] from the right side of the pattern string T, that is, by T [M-1], t [M-2],… T [0. If it is found that s [L + I + 1] is the same as a character in T, write down this position as K, 1 ≤ k ≤ m, T [k] = s [L + I + 1]. In this case, the pattern string T should be moved to the right M-K character position, that is, to the T [k] And s [L + I + 1] Alignment position. 3.
Figure 3 2nd cases of Sunday algorithm movingAnd so on. If the match is complete, the match is successful. Otherwise, move the next round until the rightmost end of the Main string s ends. The worst case of this algorithm is O (n * m ). This algorithm is faster to match short mode strings. The idea of the Sunday algorithm is similar to that of the BM algorithm. When a match fails, the next character of the last character to be matched in a text string is concerned. If this character does not appear in the matching string, skip it directly, that is, move the step size = length of the matching string + 1; otherwise, the same as the BM algorithm, the moving step = the distance from the rightmost character to the end of the matching string + 1. Here is an example: matching string: abcbczdxzc mode string: zbcac. here we can see that B-A is not correct. Then we can see the position of Z in the matching string in the mode string, then align. Match string: abcbczdxzc mode string: zbcac if there is no character in the mode string, it will jump over. Matching string: abcbcedxzcs mode string: zbcace does not appear in the mode string, so we will match the string: abcbcedxzcs mode string: zbcac
C ++ implementation of a Sunday algorithm (http://hi.baidu.com/azuryy/item/8a50f54a2f8c72e51381dad3)
/* Sunday. H */class Sunday {public: Sunday ();~ Sunday (); Public: int find (const char * pattern, const char * text); Private: void precompute (const char * pattern); Private: // Let's assume all characters are all ASCII static const int assize = 128; int _ TD [assize]; int _ patlength; int _ textlength;}; source file/* Sunday. CPP */Sunday: Sunday () {} Sunday ::~ Sunday () {} void Sunday: precompute (const char * pattern) {for (INT I = 0; I <assize; I ++) _ TD [I] = _ patlength + 1; const char * P; For (P = pattern; * P; P ++) _ TD [* p] = _ patlength-(p-pattern);} int Sunday: Find (const char * pattern, const char * text) {_ patlength = strlen (pattern); _ textlength = strlen (text); If (_ patlength <= 0 | _ textlength <= 0) Return-1; precompute (pattern); const char * T, * P, * Tx = text; while (Tx + _ patlength <= text + _ textlength) {for (P = pattern, t = TX; * P; ++ P, ++ t) {If (* P! = * T) break;} If (* P = 0) return TX-text; Tx + = _ TD [TX [_ patlength];} return-1 ;} in a simple test: int main () {char * text = "blog. csdn, blog.net "; char * pattern =" csdn, blog "; Sunday; printf (" the first occurence at: % d \ n ", Sunday. find (pattern, text); return 1 ;}
Note: In the preceding algorithm, array _ TD [] is used to record the position of each character in pattern.