[LeetCode]28. Implement strStr() ★

本文详细解析了字符串查找问题的实现,提供了Python和C语言的解决方案。Python利用内置find方法简洁高效,而C语言则通过循环和条件判断实现,展示了不同语言处理相同问题的方法差异。

题目描述

Implement strStr().

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

题目大意:字符串查找,查到返回第一次找到的下标,找不到返回-1。needle为空时返回0

样例

Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2

Example 2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

python解法

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle);

Runtime: 36 ms
Memory Usage: 13.8 MB
题后反思:

  1. python、java、C++等高级语言都实现了字符串查找这一功能

C语言解法

int strStr(char * haystack, char * needle){
    int len_b = strlen(needle);
    int len_a = strlen(haystack);
    if (len_a < len_b) return -1;

    for (int i = 0; i <= len_a-len_b; ++i) {
        int j = 0;
        while(j < len_b && haystack[j+i] == needle[j]) {
            j++;
        }
        if (j == len_b) {
            return i;
        }
    }
    return -1;
}

Runtime: 4 ms, faster than 82.13% of C online submissions for Implement strStr().
Memory Usage: 7.3 MB, less than 30.83% of C online submissions for Implement strStr().

题后反思:

  1. 用字符串长度做判断条件,可以直接规避数组越界的错误。
  2. 用’\0’做判断条件,需要时刻注意数组越界。

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值