28. 实现 strStr()

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的
第一个位置 (从0开始);
如果不存在,则返回  -1;
当 needle 是空字符串时:应返回 0 。

输入: haystack = "hello", needle = "ll"
输出: 2

输入: haystack = "aaaaa", needle = "bba"
输出: -1



思路:详见注释。
 1 class Solution(object):
 2     def strStr(self, haystack, needle):
 3         """
 4         :type haystack: str
 5         :type needle: str
 6         :rtype: int
 7         """
 8         # 若子串为空
 9         if needle == "":
10             return 0
11         # 若两串相同
12         if len(haystack) == len(needle):
13             if haystack == needle:
14                 return 0
15             else:
16                 return -1
17         # 获取两个串的长度
18         size1 = len(haystack)
19         size2 = len(needle)
20         print("两个串的长度分别是:", size1, size2)
21         for index in range(size1):
22             ans = index
23             j = 0
24             while j < size2 and ans < size1 and haystack[ans] == needle[j]:
25                 j += 1
26                 ans += 1
27             if j == size2:
28                 return index
29         return -1 if needle else 0
30 
31 if __name__ == '__main__':
32     solution = Solution()
33     print(solution.strStr("aaa", "a"))
34     print(solution.strStr("hello", "lo"))
35     print(solution.strStr("hello", "el"))