Leetcode28: Implement strStr()

内容目录

题目描述

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().

解题思路

要求查看一个字符串是否是另一个字符串的子串,可以选两个游标,对两个字符串进行一一比较。

代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(haystack.length() < needle.length()){
            return -1;
        }

        if(needle.empty()){
            return 0;
        }
        else
        {
            int i = 0, j =0;
            int count = 0;
          //  cout << haystack.length() << "," << needle.length() <<endl;
            while(i < (haystack.length()) && j < (needle.length()  )){

                if(needle[j] == haystack[i]){
                    count++;
                    i++;
                    j++;
                }else{
                    if(count != 0){
                        i = i - count + 1;
                        j = 0;
                        count = 0;
                    }else{
                        i++;
                    }
                }
                if(count == needle.length()){
                    return i - count;
                }
              //  cout << i << "," << j << "," << count <<endl;
            }
            return -1;
        }

    }
};
打赏作者