2020-01-29 刷题 实现 strStr()

题目连接:https://leetcode-cn.com/problems/implement-strstr/

题目说明:

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1


题目思想:

获取needle 字符串的第一个位置数据

指针遍历haystack 字符串的位置,并进行判断 是否与 needle 字符串的第一个位置数据 相等

相等返回位置  不等返回-1

题目代码:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         if (needle.size()==0)
 5             return 0;
 6         if (needle.size() > haystack.size())
 7             return -1;
 8         int j=0;//needle指针
 9         int i=0;
10         for (i = 0; i < haystack.size(); ++i) {
11             if (j==needle.size()){//判断完成
12                 return i - needle.size();
13             }
14             if (haystack[i] == needle[j]){
15                 j++;
16             } else{
17                 i -= j;
18                 j=0;
19             }
20         }
21         if (j==needle.size()){//判断完成
22             return i - needle.size();
23         }
24         return -1;
25     }
26 };
原文地址:https://www.cnblogs.com/gjianli/p/14347472.html