题目:

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 

思路: 指针的操作,大字符串从头到尾走,遇到与小字符串相同的就一起走,不同的就只走大字符串。小字符串走完的时候返回结果。

 

代码:

 1 class Solution {
 2   public:
 3       char *strStr(char *haystack, char *needle) {
 4           
 5           int hayLen = strlen(haystack);
 6           int needLen = strlen(needle);
 7           
 8           for(int i = 0; i <= hayLen - needLen; i++)
 9          {
10              char* p = haystack + i;
11              char* q = needle;
12              while(*q != '\0')
13              {
14                  if (*p != *q)
15                      break;
16                  else
17                  {
18                      p++;
19                      q++;
20                  }
21                    
22              }
23              if (*q == '\0')
24                  return haystack + i; 
25                       
26          }
27          
28          return NULL;
29      }
30  };

 

posted on 2013-05-07 12:01  tanghulu321  阅读(131)  评论(0编辑  收藏  举报