實現 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() 定義相符。
思路:
s1,s2分別代表第一個和第二個字符串。從s1的第一個字符開始,循環他的每個長度爲s2.length()的子串(通過 i 和 j 控制s1中的子串長度),從而進行匹配。
代碼:
java:
class Solution {
public int strStr(String haystack, String needle) {
int n1 = haystack.length();
int n2 = needle.length();
if (n2==0) {
return 0;
}
for (int i = 0; i <= n1 - n2; i++) {
for (int j = 0; j < n2; j++) {
if (haystack.charAt(i+j) != needle.charAt(j)) {
break;
}
if (j == n2 - 1) {
return i;
}
}
}
return -1;
}
}
python: