[容易]字符串查找

题目来源:http://www.lintcode.com/zh-cn/problem/strstr/

这道题注意边界条件,提交了三次才通过。

1字符串是否为NULL

2source为NULL,target不为NULL,返回0,而不是-1

采用的方法是最简单的朴素模板匹配算法。

可以accept的程序如下:

 1 class Solution {
 2 public:
 3     /**
 4      * Returns a index to the first occurrence of target in source,
 5      * or -1  if target is not part of source.
 6      * @param source string to be scanned.
 7      * @param target string containing the sequence of characters to match.
 8      */
 9     int strStr(const char *source, const char *target) {
10         // write your code here
11         if (source == NULL || target == NULL) 
12             return -1; 
13         int i=0,j=0;
14         while(i<strlen(source)&&j<strlen(target))
15         {
16             if(source[i]==target[j])
17             {
18                 i++;
19                 j++;
20             }
21             else
22             {
23                 i=i-j+1;
24                 j=0;
25             }
26         }
27         if(j==strlen(target))
28             return i-strlen(target);
29         else 
30             return -1;
31     }
32 };

可以Accept的正确程序2:

 1 class Solution {
 2  public:
 3     /**
 4      * Returns a index to the first occurrence of target in source,
 5      * or -1  if target is not part of source.
 6      * @param source string to be scanned.
 7      * @param target string containing the sequence of characters to match.
 8      */
 9     int strStr(const char *source, const char *target) {
10         if (source == NULL || target == NULL) {
11             return -1;
12         }
13         int target_size = strlen(target);
14         int source_size = strlen(source);
15         int i, j;
16         for (i = 0; i < source_size - target_size + 1; i++) {
17             for (j = 0; j < target_size; j++) {
18                 if (source[i + j] != target[j]) {
19                     break;
20                 }
21             }
22             if (j == target_size) {
23                 return i;
24             }
25         }
26         return -1;
27     }
28 };

可以Accept的正确程序3:

 1 class Solution {
 2  public:
 3     /**
 4      * Returns a index to the first occurrence of target in source,
 5      * or -1  if target is not part of source.
 6      * @param source string to be scanned.
 7      * @param target string containing the sequence of characters to match.
 8      */
 9     int strStr(const char *source, const char *target) {
10         if (source == NULL || target == NULL)
11             return -1;
12         string s(source);
13         return s.find(target);
14         return -1;
15     }
16 };
posted @ 2016-05-01 15:59  Pearl_zju  阅读(147)  评论(0编辑  收藏  举报