題目鏈接:https://www.lintcode.com/problem/implement-strstr/description?_from=ladder&&fromId=1
這是一道簡單題。
但是由於自己基礎薄弱,還是提交了好些次。
描述
For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1
.
說明
Do I need to implement KMP Algorithm in a real interview?
- Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure you confirm with the interviewer first.
樣例
Example 1:
Input: source = "source" ,target = "target"
Output: -1
Explanation: If the source does not contain the target content, return - 1.
Example 2:
Input:source = "abcdabcdefg" ,target = "bcd"
Output: 1
Explanation: If the source contains the target content, return the location where the target first appeared in the source.
挑戰
O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)
這道題用O(n2)就可以了。KMP算法由於是帶人名的算法,使用範圍並不廣,所以目前在這裏不考慮學習和使用(以後難說啊……)
我的題解:
class Solution:
"""
@param source:
@param target:
@return: return the index
"""
def strStr(self, source, target):
# Write your code here
#j = 0
if(target == ''):
return 0
for k in range(len(source)):
j = 0
for i in range(len(target)):
if(k+i >= len(source)): #沒有必要的寫法。可以參考下方題解。
break
if(source[k+i]!=target[j]):
break
j = j + 1
if(j==len(target)):
return k
return -1
九章參考題解:
# 本參考程序來自九章算法,由 @九章算法 提供。版權所有,轉發請註明出處。
# - 九章算法致力於幫助更多中國人找到好的工作,教師團隊均來自硅谷和國內的一線大公司在職工程師。
# - 現有的面試培訓課程包括:九章算法班,系統設計班,算法強化班,Java入門與基礎算法班,Android 項目實戰班,
# - Big Data 項目實戰班,算法面試高頻題班, 動態規劃專題班
# - 更多詳情請見官方網站:http://www.jiuzhang.com/?source=code
class Solution:
def strStr(self, source, target):
if source is None or target is None: #判空。顯然比我的target=''的寫法要好些
return -1
len_s = len(source)
len_t = len(target)
for i in range(len_s - len_t + 1): #這樣的寫法會更好一些。
j = 0
while (j < len_t):
if source[i + j] != target[j]:
break
j += 1
if j == len_t:
return i
return -1