-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1.按位匹配,每次发现首字母匹配则记录当前的位置,继续向后匹配。 2.如果匹配过程中发现不匹配了,则回到首字母匹配的位置+1 继续匹配。 #3
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
...ure-and-algorithms/src/main/java/com/github/liaojiacan/lintcode/Q28实现strStr/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | ||
} | ||
} |