package com.david.leetcode;
public class T28 {
//case1:回溯算法
public int strStr(String haystack, String needle) {
int m = haystack.length(), n = needle.length();
if(n==0) return 0;
//注意这里start的最大索引为m-n,因为要保证haystack的子串[start,length()]的长度>=needle.length()
for(int start=0;start<m-n+1;start++){
if(haystack.substring(start,start+n).equals(needle)) return start;
}
return -1;
}
//case2:对case1进行了改进,每次只有再起始字符相同的情况下才进行匹配
public int strStr2(String haystack, String needle) {
int m = haystack.length(), n = needle.length();
if(m<n) return -1;
if(n==0) return 0;
int hIdx = 0, nIdx = 0,currentLen = 0;
//注意hIdx能取的最大值
while(hIdx<m-n+1){
//要从与needle字串的第一个字符相等的位置开始匹配
while(hIdx<m&&haystack.charAt(hIdx)!=needle.charAt(0)) {hIdx++;}
//遍历匹配
while(hIdx<m&&nIdx<n&&haystack.charAt(hIdx)==needle.charAt(nIdx)){
hIdx++;
nIdx++;
currentLen++;
}
//匹配成功,返回start处的索引hIdx-n
if(currentLen==n) return hIdx-currentLen;
//匹配失败,haystack回溯到start+1处重新开始匹配
hIdx = hIdx-currentLen+1;
nIdx = 0;
currentLen = 0;
}
return -1;
}
}
leetcode T28
最新推荐文章于 2024-10-05 12:29:44 发布