Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
1 2 |
<strong>输入:</strong> haystack = "hello", needle = "ll" <strong>输出:</strong> 2 |
示例 2:
1 2 |
<strong>输入:</strong> haystack = "aaaaa", needle = "bba" <strong>输出:</strong> -1 |
说明:
当 needle
是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle
是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
解答
1 2 3 4 5 6 7 8 |
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ return haystack.find(needle) |
自测用例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
try: haystack = "hello" needle = "ll" result_1 = 2 result_2 = Solution().strStr(haystack, needle) print('{} - {}'.format(result_1, result_2)) except Exception as e: print(e) try: haystack = "aaaaa" needle = "bba" result_1 = -1 result_2 = Solution().strStr(haystack, needle) print('{} - {}'.format(result_1, result_2)) except Exception as e: print(e) try: haystack = "aaaaa" needle = "" result_1 = 0 result_2 = Solution().strStr(haystack, needle) print('{} - {}'.format(result_1, result_2)) except Exception as e: print(e) |
执行结果
提交时间 | 状态 | 执行用时 | 语言 |
---|---|---|---|
几秒前 | 通过 | 44 ms | python3 |