这是一道比较简单的问题,就是找出母字符串中是否有与子字符串相匹配的字符串。

要注意的就是几点,题目中要求当needle串为空时,要返回0,没有匹配的则返回 -1.

下面是题目的具体描述,haystack代表长的,needle则代表短的。

[leetcode] 28. strstr()

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.size();
        int n = needle.size();
        int i,j;
        if(m < n )
            return -1;
        if(n == 0)
            return 0;
        for(i = 0; i <= m-n ; i++)
        {
            for(j = 0; j < n; j++)
            {
                if(haystack[i+j] != needle[j])
                {
                    break;
                }
            }
            if(j == n)
                return i;
        }
        return -1;
    }
};

 

相关文章:

  • 2021-05-28
  • 2021-08-24
  • 2022-01-28
  • 2021-10-09
  • 2022-02-06
  • 2021-06-10
  • 2022-01-14
猜你喜欢
  • 2022-01-16
  • 2021-06-21
  • 2021-08-08
  • 2021-09-02
  • 2021-05-30
相关资源
相似解决方案