LeetCode-Implement strStr()的一种算法

13 篇文章 0 订阅

LeetCode-Implement strStr()的一种算法

题目链接:https://leetcode.com/problems/implement-strstr/description/

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

题目要求我们找出haystack字符串中needle字符段的所在位置,存在返回该位置,否则返回-1。

算法很简单,先判断needle字符段是否为“”,是则直接返回0即可。随后判断haystack是否为“”且needle是否不为“”,是则返回-1。
而后循环遍历haystack的每一个字符,找到对应needle的第一个字符的字符位置,判断其是否等于needle,是则返回位置,否则继续循环遍历到最后。

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle == "") return 0;	//判断
        else if (haystack == "" && needle != "") return -1;	//判断
        for (int i = 0; i < haystack.length(); i++) {	//循环遍历
            if (haystack[i] == needle[0]) {		//判断第一个字符是否相等
                int j = needle.length();
                //判断该位置开始的字符串是否存在与needle相同的部分
                if (i+j <= haystack.length() && haystack.substr(i, j) == needle) {
                    return i;
                }
            }
        }
        return -1;
    }
};

整个算法难度不大,麻烦的地方在于判断haystack或needle为“”的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值