LeetCode演算法題28:實現strStr()解析
阿新 • • 發佈:2018-11-02
實現 strStr() 函式。
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
這個題我竟然首先想到了substring類方法,但是一想那還叫什麼演算法,相當於直接用了strStr()函式,所以只能自己實現了,這個簡單的思路就是直接暴力搜尋,很簡單,直接一個個搜尋haystack然後每一個都搜尋needle長度,看是否相符。此外還需要注意題目給定的條件,當haystack長度小於needle長度時一定返回-1,此外當needle為0時返回0。
C++原始碼:
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.length ();
int len2 = needle.length();
if (len1<len2)
return -1;
if (len2==0)
return 0;
int flag = 0;
for (int i=0;i<len1-len2+1;i++)
{
for (int j=0;j<len2;j++)
if (haystack[i+j]==needle[j])
flag = 1;
else
{
flag = 0;
break;
}
if (flag == 1)
return i;
}
return -1;
}
};
python3原始碼:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len1 = len(haystack)
len2 = len(needle)
if len1<len2:
return -1
if len2==0:
return 0
flag = 0
for i in range(len1-len2+1):
for j in range(len2):
if haystack[i+j]==needle[j]:
flag = 1
else:
flag = 0
break
if flag == 1:
return i
return -1