mysql strstr_实现 strStr() 函数-算法刷题
算法題目
實現 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() 定義相符
/**
@author cosefy
@date 2020/7/2
*/
public class StrStr {
public static void main(String[] args) {
String haystack = "aaaba";
String needle = "sssssss";
int res1 = test1(haystack, needle);
System.out.println(res1);
}
//解法一
/*
思路:1,判斷模式串是否為空,空則返回0,判斷模式串的長度是否大于主串,大于則返回-1.
2,如果子串和主串第一個字符不相同則直接向后移動主串
3,如果部分匹配,則需要主串回退,此處可以利用一個輔助變量代替主串前進,可以省略回退。
*/
private static int test1(String haystack, String needle) {
int n = needle.length();
if (n == 0)
return 0;
int h = haystack.length();
if (n > h)
return -1;
for (int i = 0; i < h - n + 1; i++) {
int temp = i, j = 0; //利用temp變量來代替主串元素往后比較,可以省略匹配失敗后主串的回退
for (; j < n; j++) {
if (haystack.charAt(temp++) != needle.charAt(j))
break;
}
if (j == n) //第二個for循環完全執行完之后j=n,說明完全匹配。
return i;
}
return -1;
? }
? //解法二:KMP算法
}
總結
以上是生活随笔為你收集整理的mysql strstr_实现 strStr() 函数-算法刷题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql webhook_sql 数据
- 下一篇: python伪装浏览器什么意思_用pyt