Leetcode-28. Implement strStr()
2016-10-02 15:42
375 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这个题目有点略无语,其实就是实现一个字符串子串位置的算法。String已经自带这个功能了。Your runtime beats 63.74% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
当然这种找子串的也可以用最麻烦的两重循环O(n*m),n是haystack的长度,m是needle的长度。Your runtime beats 26.44% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() == 0 && needle.length() == 0) return 0;
if(needle.length() == 0) return 0;
if(needle.length() > haystack.length())return -1;
for(int i = 0 ; i < haystack.length()-needle.length() + 1; i ++){
int index = i,j = 0;
boolean isSubStr = true;
while(index < haystack.length() && j < needle.length()){
if(haystack.charAt(index) != needle.charAt(j)){
isSubStr = false;
break;
}
index ++; j ++;
}
if(isSubStr && j == needle.length()) return (index - needle.length());
}
return -1;
}
}当然还有一些改进的匹配算法,比如KMP什么的,就暂时不管了
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这个题目有点略无语,其实就是实现一个字符串子串位置的算法。String已经自带这个功能了。Your runtime beats 63.74% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
当然这种找子串的也可以用最麻烦的两重循环O(n*m),n是haystack的长度,m是needle的长度。Your runtime beats 26.44% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() == 0 && needle.length() == 0) return 0;
if(needle.length() == 0) return 0;
if(needle.length() > haystack.length())return -1;
for(int i = 0 ; i < haystack.length()-needle.length() + 1; i ++){
int index = i,j = 0;
boolean isSubStr = true;
while(index < haystack.length() && j < needle.length()){
if(haystack.charAt(index) != needle.charAt(j)){
isSubStr = false;
break;
}
index ++; j ++;
}
if(isSubStr && j == needle.length()) return (index - needle.length());
}
return -1;
}
}当然还有一些改进的匹配算法,比如KMP什么的,就暂时不管了
相关文章推荐
- LeetCode 28. Implement strStr()
- 【C++】【LeetCode】28. Implement strStr()
- leetcode 28. Implement strStr() KMP 算法
- leetcode 28. Implement strStr()
- leetcode刷题记录-28. Implement strStr()
- leetcode 28. Implement strStr() 三种解法
- LeetCode 28. Implement strStr()
- 算法作业HW27:LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr()
- 小白笔记-----------------------leetcode(28. Implement strStr())
- 28. Implement strStr() LeetCode
- leetcode 28. Implement strStr()
- [Leetcode]28. Implement strStr()
- Leetcode 28. Implement strStr() (Easy) (cpp)
- [置顶] 【leetcode】28. Implement strStr()(Python & C++)(KMP算法)
- [LeetCode] 28. Implement strStr() java
- leetcode 28. Implement strStr()
- [leetcode]: 28. Implement strStr()
- leetcode 28. Implement strStr()
- Leetcode: 28. Implement strStr()