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

Problem: 28. 找出字符串中第一个匹配项的下标

文章目录

  • 思路
  • 解题方法
  • Code
    • Code: pythonic method, find()一行解决
    • Code: 暴力匹配

思路

参考:

  • Python String find() method
  • 实现 strStr()
  • 此题也确实可以用 KMP,sunny等更高级的单模匹配算法解决。

解题方法

  1. 可以用一种很pythonic的方法解决,即直接调用find()方法,比较取巧;
  2. 简单直接的暴力匹配法在这里也值得学习。

Code

Code: pythonic method, find()一行解决

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
	    # find()方法秒解
        return haystack.find(needle)

Code: 暴力匹配

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        # 确认需要匹配的字符串的长度
        len_match = len(needle)

        # 逐个匹配,注意末尾几个有些不用匹配
        for i in range(len(haystack) - len_match + 1):
            # 进行匹配,注意切片写法
            if haystack[i : i+len_match] == needle:
                # 匹配成功
                return i 
        # 未能匹配,返回-1
        return -1

你可能感兴趣的:(python,开发语言,leetcode,数据结构,算法)