算法描述 :
實現(xiàn)strStr()函數(shù)。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當(dāng) needle 是空字符串時,我們應(yīng)當(dāng)返回什么值呢?這是一個在面試中很好的問題。
對于本題而言,當(dāng) `needle` 是空字符串時我們應(yīng)當(dāng)返回 0 。這與C語言的 strstr()以及 Java的indexOf() 定義相符。
算法實現(xiàn) :
Java實現(xiàn) :
class Solution {
public int strStr(String haystack, String needle) {
if ("".equals(needle)) {
return 0;
}
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) != needle.charAt(0)) { // haystack逐個字符與needle第一個字符比較
continue;
}
// 從第一個相同字符開始向后掃描比較
for (int j = 0; j < needle.length(); j++) {
if (i + j < haystack.length()) {
if (haystack.charAt(i + j) != needle.charAt(j)) { // 如某個字符不相等,則i+1重新來過
break;
}
} else {
return -1;
}
if (j == needle.length() - 1) { // 比較到needle最后一個字符, 返回haystack的索引
return i;
}
}
}
return -1;
}
}