LeetCode 28. Implement strStr()
2016-10-20 10:25
399 查看
题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
给定2个字符串"needle"和"haystack",找出“needle”在"haystack"中出现的第一次位置,
否则返回-1
题解:
使用自带index()函数:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle not in haystack:
return -1
else:
return haystack.index(needle)
不使用内置函数:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
给定2个字符串"needle"和"haystack",找出“needle”在"haystack"中出现的第一次位置,
否则返回-1
题解:
使用自带index()函数:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle not in haystack:
return -1
else:
return haystack.index(needle)
不使用内置函数:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
相关文章推荐
- leetCode 28. Implement strStr() 字符串
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr() 实现strStr()函数
- LeetCode 28. Implement strStr()
- [LeetCode]28. Implement strStr()
- 【LeetCode】28. Implement strStr()
- leetcode 28. Implement strStr()
- Leetcode:28. Implement strStr()(JAVA)
- 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()(Python & C++)(KMP算法)
- 个人记录-LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr()