題目:
實作 strStr() 函式,
給你兩個字串 haystack 和 needle ,請你在 haystack 字串中找出 needle 字串出現的第一個位置(下標從 0 開始),如果不存在,則回傳 -1 ,
說明:
當 needle 是空字串時,我們應當回傳什么值呢?這是一個在面試中很好的問題,
對于本題而言,當 needle 是空字串時我們應當回傳 0 ,這與 C 語言的 strstr() 以及 Java 的 indexOf() 定義相符,
示例 1:
輸入:haystack = "hello", needle = "ll"
輸出:2
示例 2:
輸入:haystack = "aaaaa", needle = "bba"
輸出:-1
示例 3:
輸入:haystack = "", needle = ""
輸出:0
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
暴力解法:
package StrStr;
public class StrStr {
public int strStr(String haystack, String needle) {
//如果needle本身小于haystack,那直接回傳-1
if (haystack.length() < needle.length()) {
return -1;
}
//如果needle為空,則回傳0
if (needle.length() == 0) {
return 0;
}
int count = 0;
int result = 0;
int i = 0;
outer:
for (i = 0; i <= haystack.length() - needle.length(); i++) {
for (int j = 0; j < needle.length(); j++) {
//如果needle第j個字符與haystack第i+j個字符相等,那么計數+1
if (needle.charAt(j)==haystack.charAt(i+j)) {
count++;
//如果計數count等于needle長度,那么查找成功,break
if(count == needle.length()) {
result = count;
break outer;
}
}
}
//每輪外回圈開始前,count都需要歸零
count = 0;
}
if (result == needle.length()) {
return i;
}else {
return -1;
}
}
public static void main(String[] args) {
StrStr test = new StrStr();
String haystack = "aaaaa";
String needle = "bba";
System.out.println(test.strStr(haystack, needle));
}
}
KMP解法:
力扣
https://leetcode-cn.com/problems/implement-strstr/solution/shua-chuan-lc-shuang-bai-po-su-jie-fa-km-tb86/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299541.html
標籤:其他
