28 leetcode - Implement strStr()

本文提供了一个简单的Python程序,用于实现字符串查找功能。通过自定义的方法strStr,在字符串haystack中查找子串needle首次出现的位置,若未找到则返回-1。适用于初学者了解字符串的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
中文:字符串a和b,返回b在a的位置,如果a不包含b返回-1
'''
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        len_haystack,len_needle = len(haystack),len(needle)

        if len_needle == 0:  #needle为空
            return 0

        if len_needle > len_haystack: #needle长度大于haystack,肯定匹配不上
            return -1

        i = 0
        while i < len_haystack - len_needle + 1:  #比较的字符串长度需要大于等于needle,比needle还短的话没必要比较
            j = 0
            flag = True
            while j < len_needle:
                if haystack[i + j] != needle[j]:
                    flag = False
                    break
                j += 1

            if flag == True:
                return i
            i += 1

        return -1

if __name__ == "__main__":
    s = Solution()
    print s.strStr('abc','bcd')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值