Skip to content

Commit

Permalink
leetcode:Q28实现strStr
Browse files Browse the repository at this point in the history
1.按位匹配,每次发现首字母匹配则记录当前的位置,继续向后匹配。
2.如果匹配过程中发现不匹配了,则回到首字母匹配的位置+1 继续匹配。

#3
  • Loading branch information
0xbitboy committed Jan 30, 2019
1 parent 2f2b89e commit 93913eb
Showing 1 changed file with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.github.liaojiacan.lintcode.Q28实现strStr;

/**
* @author liaojiacan
* @date 2019/1/30
*/
class Solution {
public int strStr(String haystack, String needle) {

if("".equals(needle)){
return 0;
}

if(needle.length()>haystack.length()){
return -1;
}
char[] haystackChars = haystack.toCharArray();
char[] needleChars = needle.toCharArray();
int index = -1;
int p = 0;
for(int i=0;i<haystackChars.length;++i){

if(p < needleChars.length && haystackChars[i] == needleChars[p]){
p++;
if(index == -1){
index = i;
}
if(p==needleChars.length){
return index;
}
}else{
p=0;
if(index != -1){
i = index;
}
index = -1;
}

}

return -1;
}

public static void main(String[] args) {
System.out.println(new Solution().strStr("mississippi","pi"));
}
}

0 comments on commit 93913eb

Please sign in to comment.