strStr解题报告

题目意图:identify the target string from source string

思路: 1. 对于比较连续的2个string 需要做循环去找起始位置。 本题为一个target和一个source,则只需要一个循环去找source里面的起始位置。 对于找2个string里面的longest common substring 则需要用2重的for 循环去寻找两个起始位置。
      2. 注意for循环结束位置的控制  

 

初始化部分:

      我的代码:

  if (source == null || target == null || 
            target.length() > 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 
 3            target.length() > source.length()) {
 4 
 5             return -1;
 6 
 7         }
 8 
 9         if (target.length() == 0) {
10 
11             return 0;
12 
13         }
14 
15         int m = source.length();
16 
17         int n = target.length();

九章答案:

if (source == null || target == null) { return -1; }

reflection:
               1.对于target和source的长度的判断在循环体内可以返回正确的结果,不需要当作特例。
    2.对于空和长度为0的特例初始化,先判断是否为null部分,否则为null时取length会报错。
    3. 对于target长度为0的情况,可以通过循环题处理。

循环体部分:

   我的代码:

 for (int i = 0; i <= m - n; i++) {
            for (int j = 0; j < n; j++) {
                if (source.charAt(i + j) != target.charAt(j)) {
                    break;
                }
                if (j == n - 1) {
                    return i;
                }
            }
        }
        return -1;  

九章答案:

 在外层循环的定义一个变量,当内层循环结束时,判断该变量的值。这样就可以处理长度为0的特殊情况。

 链接:       http://www.jiuzhang.com/solutions/strstr/

 
原文地址:https://www.cnblogs.com/jiangchen/p/5393846.html