28. Implement strStr()查找字符串第一次出现的位置Python

当查找的字符串为空空时返回0,当不存在查找的字符串时返回-1

Input: 'telephone', needle='el'

Output:1

Input; 'whatever', needle=' '

Output; 0

Input; 'soWhat', needle='os'

Output: -1

    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle)==0:
            return 0    
        elif needle in haystack:
            return haystack.index(needle)
        else:
            return -1

Runtime:20ms

你可能感兴趣的:(Leetcode(Easy))