DEV Community

Woody
Woody

Posted on

Leetcode刷题篇语法恶补 函数注解(Function Annotations)

python3X

你提到的这一行代码是标准的 Python 语法:

函数注解Function Annotations
Enter fullscreen mode Exit fullscreen mode
def strStr(haystack: str, needle: str) -> int:
    return haystack.find(needle)
Enter fullscreen mode Exit fullscreen mode

下面我逐部分解释它的语法含义:


🔍 1. def strStr(haystack: str, needle: str) -> int:

这是 函数定义语法:

  • def:表示定义一个函数。
  • strStr:函数名,类似 LeetCode 的函数签名要求。
  • haystack: str:表示参数 haystack 是一个字符串(str 类型注解)。
  • needle: str:表示参数 needle 也是字符串。
  • -> int:表示这个函数返回一个整数(return type annotation)。

这是 Python 3 中的 函数注解(Function Annotation)写法,不是强制类型,而是一种提示。

normal writing

def strStr(haystack, needle):
    return haystack.find(needle)

Enter fullscreen mode Exit fullscreen mode

✅ 2. return haystack.find(needle)

这是返回语句:

  • haystack.find(needle) 是 Python 字符串的内置方法:

    • 它会返回 needlehaystack 中第一次出现的 起始索引
    • 如果找不到,返回 -1

比如:

haystack = "sadbutsad"
needle = "sad"
haystack.find(needle)  # 返回 0
Enter fullscreen mode Exit fullscreen mode

📌 总结整行含义:

这是一个函数 strStr,接收两个字符串 haystackneedle,返回 needlehaystack 中第一次出现的位置。如果没有,返回 -1。

📘 拆解说明:
语法部分 说明
def 定义函数的关键词(define)
strStr 函数名
haystack: str 给参数 haystack 添加类型注解,表示它是 str 类型
needle: str 参数 needle 也是 str 类型
-> int 表示函数的返回值应该是 int 类型
: 语句块开始,缩进体是函数体
return haystack.find(needle) 函数体,返回字符串匹配的位置

这个实现用的是 Python 的内置方法 str.find(),非常简洁。


如果你还没学过 Python 的类型注解,或者希望用更基础的写法,也可以写成:

def strStr(haystack, needle):
    return haystack.find(needle)
Enter fullscreen mode Exit fullscreen mode

效果是一样的,只是少了类型提示。


如果你还想深入了解 .find().index() 的区别或要看底层实现,也可以告诉我。

Top comments (0)