[LeetCode]Implement strStr()
2017-07-13 07:59
405 查看
Description:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解析:
这是算法中比较经典的问题,判断一个字符串是否是另一个字符串的子串。这个题目最经典的算法应该是KMP算法,不熟悉的朋友可以参见Knuth–Morris–Pratt algorithm。KMP算法是最优的线性算法,复杂度已经达到这个问题的下限。但是KMP算法比较复杂,很难在面试的短时间里面完整正确的实现。所以一般在面试中并不要求实现KMP算法。
下面我们先说说brute force的算法,假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m+1个子串,所以算法时间复杂度为O((n-m+1)*m)=O(n*m),空间复杂度是O(1)。
code:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解析:
这是算法中比较经典的问题,判断一个字符串是否是另一个字符串的子串。这个题目最经典的算法应该是KMP算法,不熟悉的朋友可以参见Knuth–Morris–Pratt algorithm。KMP算法是最优的线性算法,复杂度已经达到这个问题的下限。但是KMP算法比较复杂,很难在面试的短时间里面完整正确的实现。所以一般在面试中并不要求实现KMP算法。
下面我们先说说brute force的算法,假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m+1个子串,所以算法时间复杂度为O((n-m+1)*m)=O(n*m),空间复杂度是O(1)。
code:
public int strStr(String haystack, String needle) { int m = haystack.length(); int n = needle.length(); if(m<n)return -1; if(n==0)return 0; int length = m-n+1; for(int i=0;i<length;i++){ if((haystack.substring(i,n)).equals(needle)){ return i; } n++; } return -1; }
相关文章推荐
- LeetCode 028 Implement strStr()
- leetcode Implement strStr()
- Leetcode: Implement strStr()
- leetcode Implement strStr()
- 和大神们学习每天一题(leetcode)-Implement strStr()
- [leetcode]Implement strStr()
- leetcode--Implement strStr()
- [LeetCode] Implement strStr()
- leetcode(57)- Implement strStr()
- LeetCode Implement strStr()
- [LeetCode] Implement strStr()[字符串hash]
- LeetCode Implement strStr()
- 【LeetCode】28 - Implement strStr()
- 28 leetcode - Implement strStr()
- 【Leetcode】【Easy】Implement strStr()
- LeetCode: Implement strStr()
- leetcode-28-Implement strStr()
- LeetCode: Implement strStr()
- LeetCode-难题集之Implement strStr()与KMP算法
- LeetCode:Implement strStr()