leetcode 28.找出字符串中第一个匹配项的下标(python版)

需求

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。
如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:“sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:“leeto” 没有在 “leetcode” 中出现,所以返回 -1 。

代码

class Solution:
    def str_str(self,haystack,needle):
        try:
            # str.index(sub [, start [, end]])
            # str 表示要进行查找的原始字符串;sub 代表要查找的子字符串;start 和 end 分别表示字符串查找的起始和结束位置
            # index() 函数返回的是子字符串在字符串中的索引位置,如果没有找到该子字符串,则抛出 ValueError 异常。
            index = haystack.index(needle)
            return index
        except ValueError:
            return -1

if __name__ == '__main__':
    call=Solution()
    haystack1 = "leetcode"
    needle1= "leeto"
    haystack2 = "sadbutsad"
    needle2= "sad"
    print(call.str_str(haystack1, needle1))
    print(call.str_str(haystack2, needle2))

运行结果

leetcode 28.找出字符串中第一个匹配项的下标(python版)_第1张图片

你可能感兴趣的:(leetcode,算法,python,职场和发展)