【LeetCode 28】Implement strStr() (Python)
来源:互联网 发布:做微信动图软件叫什么 编辑:程序博客网 时间:2024/06/16 11:30
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目分析:判断needle给出的字符串是否是haystack给出的字符串的子串。如果是返回needle第一个字符在haystack出现的位置。
示例:
Input: haystack = “hello”, needle = “ll”
Output: 2
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
方法一:
- 思路:检测字符串是否包含某字符串时,在python中有两个现成的方法—–index()和find()。
- 优点:代码短,简单。直接就可以返回对应位置。 时间复杂度O(1)。
缺点:有局限性,只适用于这道题。 - 代码:
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type n eedle: str :rtype: int """ if needle in haystack: return haystack.find(needle) else: return -1
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type n eedle: str :rtype: int """ if needle in haystack: return haystack.index(needle) else: return -1
方法二:
- 思路:循环haystack(不全循环,只到needle首字母出现的位置即可),当遇到与needle首字母相同时,检查haystack从该位置开始的与needle长度相同的部分的内容是否相同。如果是返回首字母出现的位置,否则返回-1。
- 优点:换一部分代码就可用于其他情况,适用范围广。也好懂。
缺点:代码较长。时间复杂度应该是O(n)吧(这个因为包含了好几个if还有while所以不太会算,好像还要结合概率论。会算的可以在评论里教教我,不胜感激) - 代码:
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type n eedle: str :rtype: int """ if not needle: return 0 for i in range(len(haystack)-len(needle)+1): if haystack[i]==needle[0]: j=1 #用来记数needle已经检查了几个字母 while j<len(needle) and haystack[i+j]==needle[j]: j+=1 if j==len(needle): return i return -1
阅读全文
2 0
- 【LeetCode 28】Implement strStr() (Python)
- Leetcode-Implement strStr()-Python
- 【Leetcode】【python】Implement strStr()
- LeetCode--Implement strStr() Python
- LeetCode(28)Implement Strstr()
- [leetcode 28] Implement strStr()
- LeetCode[28]Implement strStr()
- leetcode-28 Implement strStr()
- [LeetCode 28]Implement strStr()
- leetcode 28 Implement strStr()
- Leetcode 28 Implement strStr()
- LeetCode 28 - Implement strStr()
- LeetCode 28:Implement strStr()
- leetcode 28 -- Implement strStr()
- leetcode[28]:Implement strStr()
- leetcode 28: Implement strStr()
- Leetcode #28 Implement strStr()
- leetCode #28 Implement strStr()
- 《Spring Microservices in Action》(Manning 2016)中文版目录
- django restframework(serializer & queryset & model)
- [Leetcode][python]Copy List with Random Pointer
- [437]. Path Sum III,[687]. Longest Univalue Path
- 欠拟合(Underfitting) & 过拟合(Overfitting) & 正则化(Regularization)
- 【LeetCode 28】Implement strStr() (Python)
- Bailian2735 八进制到十进制【入门】(POJ NOI0113-46)
- 【mysql】创建用户 授权
- Bailian2887 能被3,5,7整除的数【入门】
- wamp配置(php, mysql, apache)
- Bailian2734 十进制到八进制【入门+八进制】(POJ NOI0113-45)
- 在Mac OS中配置CMake的详细图文教程
- Bailian2689 大小写字母互换【入门+文本处理】(POJ NOI0107-14)
- spring的@Transactional注解详细用法