【leetcode】28. 实现strStr() 【字符串】

版权声明:本文为博主原创文章,转载请注明出处-- https://blog.csdn.net/qq_38790716/article/details/89761581

实现 s t r S t r ( ) strStr() 函数。

给定一个 h a y s t a c k haystack 字符串和一个 n e e d l e needle 字符串,在 h a y s t a c k haystack 字符串中找出 n e e d l e needle 字符串出现的第一个位置 (从 0 0 开始)。如果不存在,则返回 1 -1

示例 1:

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

示例 2:

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

思路:

1)从 h a y s t a c k haystack 中某个字符开始匹配,当与 n e e d l e needle 完全匹配时,返回 h a y s t a c k haystack 字符下标;如果某个字符与 n e e d l e needle 内字符不匹配,则 b r e a k break ;如遍历完 h a y s t a c k haystack 仍未找到则返回 1 -1

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

2)调用函数 s u b s t r substr 截取字符串进行匹配。以 h a y s t a c k haystack 中某个字符开始,截取长度等于 n e e d l e needle 长的字符串与 n e e d l e needle 进行匹配,若匹配返回下标

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

猜你喜欢

转载自blog.csdn.net/qq_38790716/article/details/89761581