补充:本方法从最终原理上并不比普通的对子序列从前向后比较高效(因为原理是相同的),但针对力扣的测试用例速度提升蛮大的)
原文:
除了蛮力算法和KMP算法,也可以采用对子序列从后向前比较的方式,代码如下
class Solution {
public int strStr(String haystack, String needle) {
int length1=haystack.length();
int length2=needle.length();
if(length2==0) return 0;
int i=length2-1;
int j=length2-1;
int s=0;
while(i<length1&&j>=0){
if(haystack.charAt(i)==needle.charAt(j)) {
i--;
j--;
s++;
if(s==length2) return i+1;
}
else if(haystack.charAt(i)!=needle.charAt(j)){
j=length2-1;
i=i+s+1;
s=0;
while(i<length1&&haystack.charAt(i)!=needle.charAt(j)){
i++;
} }
}return -1;
}}
效率