題目來源:
https://leetcode.com/problems/implement-strstr/description/
題目分析:
輸入兩個字符串haystack和needle,如果needle是haystack的一個子串,那麼返回這個子串在haystack出現的第一個位置,否則返回-
解決代碼:
一開始看到這個題目,腦海出來的就是“in”和“not in”的用法,後來在如何找到下標那遇到問題。看到別人有用到.index()函數,解決問題。
先來解釋一下index()函數的相關用法。http://www.runoob.com/python/att-string-index.html
具體來說,它用來檢測字符串中是否包括子串。如果包括的話,返回子串開始的索引,否則拋出異常。
則我解決的代碼爲:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle in haystack:
return haystack.index(needle)
else:
return (-1)
除此以外,還可以暴力檢索。將needle看成一個整體,一塊一塊的去比較,如果有,返回下標i,否則返回-1.
class Solution:
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