leetCode 28. Implement strStr() 字符串

简介:

28. Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


haystack中找与needle 第一个相匹配的位置。如果找不到,返回-1。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    int strStr(string haystack, string needle) {
        if(haystack.size() == 0 && needle.size() == 0)
            return 0;
        if(needle.size() == 0)
            return 0;
        if(haystack.size() < needle.size())
            return -1;
        for(int i = 0;i < haystack.size() - needle.size() + 1;i++)
        {
            bool flag = true;
            if(needle[0] == haystack[i])
            {
                int j = 0;
                for(; j < needle.size();j++)
                {
                    if(needle[j] != haystack[i+j])
                    {
                        flag = false;
                        break;
                    }
                         
                }
                if(flag)
                    return i;
            }
        }
        return -1;
    }
};

本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836727


相关文章
|
4天前
|
C++
Leetcode第43题(字符串相乘)
本篇介绍了一种用C++实现的字符串表示的非负整数相乘的方法,通过逆向编号字符串,将乘法运算转化为二维数组的累加过程,最后处理进位并转换为字符串结果,解决了两个大数相乘的问题。
19 9
|
4天前
|
算法 C++
Leetcode第八题(字符串转换整数(atoi))
这篇文章介绍了LeetCode上第8题“字符串转换整数(atoi)”的解题思路和C++的实现方法,包括处理前导空格、正负号、连续数字字符以及整数溢出的情况。
10 0
|
4天前
【LeetCode 22】459.重复的子字符串
【LeetCode 22】459.重复的子字符串
13 0
|
4天前
【LeetCode 21】28. 实现 strStr()
【LeetCode 21】28. 实现 strStr()
14 0
|
4天前
【LeetCode 20】151.反转字符串里的单词
【LeetCode 20】151.反转字符串里的单词
9 0
|
4天前
【LeetCode 19】541.反转字符串II
【LeetCode 19】541.反转字符串II
9 0
|
4天前
【LeetCode 18】6.2.反转字符串
【LeetCode 18】6.2.反转字符串
9 0
|
2月前
|
存储 算法
LeetCode第43题字符串相乘
LeetCode第43题"字符串相乘"的解题方法,通过使用数组存储乘积并处理进位,避免了字符串转换数字的复杂性,提高了算法效率。
LeetCode第43题字符串相乘
|
2月前
|
算法 Java
LeetCode第28题找出字符串中第一个匹配项的下标
这篇文章介绍了LeetCode第28题"找出字符串中第一个匹配项的下标"的两种解法:暴力解法和KMP算法,并解释了KMP算法通过构建前缀表来提高字符串搜索的效率。
LeetCode第28题找出字符串中第一个匹配项的下标
|
2月前
|
算法
LeetCode第8题字符串转换整数 (atoi)
该文章介绍了 LeetCode 第 8 题字符串转换整数 (atoi)的解法,需要对字符串进行格式解析与校验,去除前导空格和处理正负号,通过从高位到低位的计算方式将字符串转换为整数,并处理越界情况。同时总结了这几道题都需要对数字的表示有理解。
LeetCode第8题字符串转换整数 (atoi)