[Leetcode] Implement strStr() (Java)
2013-12-28 15:07
441 查看
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
比较字符串,查找haystack中是否包含needle,如果包含则返回haystack中首先出现needle的指针,如果不包含则返回null
KMP算法,over[]代表覆盖度,从-1开始记,n代表 (n+1)个与模式串开头重复数
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
比较字符串,查找haystack中是否包含needle,如果包含则返回haystack中首先出现needle的指针,如果不包含则返回null
KMP算法,over[]代表覆盖度,从-1开始记,n代表 (n+1)个与模式串开头重复数
public class ImplementstrStr { public String strStr(String haystack, String needle) { if(haystack==null||needle==null||needle.length()>haystack.length()) return null; if(needle.length()<1) return haystack; int[] over = new int[needle.length()]; over[0]=-1; int preover; for(int i=1;i<needle.length();i++){ preover = over[i-1]; while(preover>=0&&needle.charAt(i)!=needle.charAt(preover+1)){ preover = over[preover]; } if(needle.charAt(i)==needle.charAt(preover+1)) over[i]=preover+1; else over[i]=-1; } int i=0,j=0; while(i<haystack.length()&&j<needle.length()){ if(haystack.charAt(i)==needle.charAt(j)){ i++; j++; }else if(j==0){ i++; }else { j=over[j-1]+1; } } if(j==needle.length()) return haystack.substring(i-j); return null; } public static void main(String[] args) { String haystack = "ababab135ab"; String needle = "ab1"; System.err.println(new ImplementstrStr().strStr(haystack, needle)); } }
相关文章推荐
- Java [leetcode 28]Implement strStr()
- LeetCode 28 : Implement strStr() (Java)
- LeetCode – Implement strStr() (Java)
- LeetCode-Easy-Java-Implement strStr()
- [LeetCode][Java] Implement strStr()
- LeetCode : Implement strStr() [java]
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- LeetCode 28 — Implement strStr()(C++ Java Python)
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- Java for LeetCode 028 Implement strStr()
- leetcode - Implement strStr()
- LeetCode Implement strStr()
- 【LeetCode】C# 28、Implement strStr()
- LeetCode-Easy刷题(9) Implement strStr()
- LeetCode - Implement strStr()
- [leetcode]Implement strStr()
- LeetCode 028 Implement strStr()
- leetcode(57)- Implement strStr()
- LeetCode:Implement strStr()
- LeetCode28:Implement strStr()