日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Leet Code OJ 28. Implement strStr() [Difficulty: Easy]

發(fā)布時(shí)間:2024/2/28 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 28. Implement strStr() [Difficulty: Easy] 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

翻譯:
實(shí)現(xiàn)一個(gè)方法strStr()。返回字符串needle第一次在字符串haystack出現(xiàn)的下標(biāo),如果needle不是haystack的一部分,就返回-1。

分析:
在文本中查找某個(gè)模式出現(xiàn)的位置的算法,稱為字符串匹配算法。常用的方法有樸素字符串匹配算法、KMP算法等。樸素字符串匹配算法,就是把2個(gè)字符串頭部對(duì)齊,然后逐一字符匹配,失配后,把needle右移一位,繼續(xù)從頭匹配。我們這里采用KMP算法。

代碼:

public class Solution {/*** 改進(jìn)的Next指針?biāo)惴?* @param s* @return*/private int[] getNext(String s) {int[] next = new int[s.length()];next[0] = 0;if (s.length() == 1) {return next;}next[1] = 0;int i = 1;int j = 0;while (i < s.length() - 1) {if (s.charAt(i) == s.charAt(j)) {j++;i++;if (s.charAt(i) == s.charAt(j)) {next[i] = next[j - 1];} else {next[i] = j;}} else {if (j == 0) {i++;next[i] = 0;} else {j = next[j];}}}return next;}/*** KMP字符串匹配算法** @param s* @return*/public int strStr(String haystack, String needle) {if (needle.length() == 0) {return 0;}int[] next = getNext(needle);int index = -1;int i = 0;int j = 0;while (i < haystack.length()) {if (haystack.charAt(i) == needle.charAt(j)) {if (j == needle.length() - 1) {return i - j;}i++;j++;} else {if (j == 0) {i++;} else {j = next[j];}}}return index;} }

總結(jié)

以上是生活随笔為你收集整理的Leet Code OJ 28. Implement strStr() [Difficulty: Easy]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。