美文网首页
LeetCode 28. Implement strStr()

LeetCode 28. Implement strStr()

作者: 洛丽塔的云裳 | 来源:发表于2020-04-09 00:29 被阅读0次

0. 题目

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

1. C++版本

注意,当haystack字符串更短的时候,不要交换haystack和needle,多次一举。"mississippi" "issip"这种特例

 if (needle.empty())
            return 0;
        int i = 0, j = 0, firstIndex = -1, flag=0;
        for (;i<haystack.size() && j<needle.size(); ) {
            if (needle[j] == haystack[i]) {
               if (flag == 0) {
                   firstIndex = i;
                   flag = 1;
               }
              i++;j++;
            }
            else {
               if (firstIndex != -1) {
                   i = firstIndex;
                   j = 0;
               }
               i++;
               firstIndex = -1;
               flag = 0;
            }
        }
        if (j != needle.size())
            return -1;
        return firstIndex;
    }

2. python版本

TODO

相关文章

网友评论

      本文标题:LeetCode 28. Implement strStr()

      本文链接:https://www.haomeiwen.com/subject/zduephtx.html