Topic Intent: Identify the target string from source string
Idea: 1. For a comparison of 2 consecutive strings, a loop is needed to find the starting position. This is titled a target and a source, you only need a loop to find the starting position within the source. For the longest common substring with 2 strings, a 2-heavy for loop is needed to find two starting positions.
2. Note the control of the For Loop end position
Initialization section:
My Code:
if NULL Null | | > Source.length ()) { return-1; } if (target.length () = = 0) {return 0; } int m = source.length (); int n = target.length ();
1 if(Source = =NULL|| target = =NULL||2 3Target.length () >source.length ()) {4 5 return-1;6 7 }8 9 if(target.length () = = 0) {Ten One return0; A - } - the intm =source.length (); - - intn = target.length ();
The answer to the nine chapters:
if NULL NULL return -1; }
Reflection
1. The judgment of the length of target and source can return the correct result in the body of the loop, and does not need to be treated as a special case.
2. For the exception of NULL and length 0 initialization, first determine whether the null part, otherwise null when the length will be an error.
3. For a target length of 0, it can be processed by a cyclic problem.
Part of the Loop body:
My Code:
for (int i = 0; I <= m-n; i++) { for (int j = 0; J < N; j + +) {
8>if (Source.charat (i + j)! =
Target.charat (j)) {break
; }
if (j = = N-1
) {
return
i; }} }
return -1;
The answer to the nine chapters:
A variable is defined in the outer loop, and when the inner loop ends, the value of the variable is judged. This allows you to handle special cases with a length of 0.
Links: http://www.jiuzhang.com/solutions/strstr/
Strstr Problem Solving Report