Leetcode之Implement strStr() 问题

来源:互联网 发布:阿里云数据分析 编辑:程序博客网 时间:2024/05/18 23:57

问题描述:

Implement strStr().

Returns the index of the first occurrence of needle(针) in haystack(干草堆), or -1 if needle is not part of haystack.

题目来源:Implement strStr() (详细地址:https://leetcode.com/problems/implement-strstr/description/)

思路分析:感觉直接翻译题目的意思有股怪怪的味道,其实它的意思就是我要在一个字符串中找到另一个字符串,并记录下第一次出现的位置(索引)。我们可以动用两个指针,一个指针i遍历父字符串(即haystack),另外一个指针j指向子字符串(即needle),然后如果索引i开始的字符串,每个位置都和子字符串正好匹配,我们就返回当前i的索引;如果有一个位置不匹配(即haystack[i + j] != needle[j]),我们就让i往下走,看看接下来有没有匹配的。

代码:




原创粉丝点击