LeetCode28. Implement strStr()
2017-06-06 11:04
323 查看
题目
Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路
就是一个找子串的函数。先顺势扫描,寻找首字母的匹配项,之后利用subString函数看剩余串是否匹配,如果匹配则最终返回i;寻找下一个首字母匹配位置;直到循环结束。
代码
public class Solution {public int strStr(String haystack, String needle) {
if(needle.length() == 0 && haystack.length() == 0) return 0;
if(haystack.length() == 0 || haystack.length() < needle.length()) return -1;
if(needle.length() == 0) return 0;
int strStr = -1;
int length = needle.length();
char firstOfNeedle = needle.charAt(0);
for(int i = 0; i < (haystack.length() - length + 1) ; ++ i){
if(firstOfNeedle == haystack.charAt(i)){
if(haystack.substring(i , i + length).equals(needle)) return i;
}
}
return strStr;
}
}
相关文章推荐
- Leetcode28. Implement strStr()
- 28. Implement strStr()-leetcode-java
- 【leetcode】28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode:28. Implement strStr()
- 【一天一道LeetCode】#28. Implement strStr()
- LeetCode 28. Implement strStr()
- Leetcode-28. Implement strStr()
- LeetCode笔记:28. Implement strStr()
- python写算法题:leetcode: 28. Implement strStr()
- Leetcode—— 28. Implement strStr()
- LeetCode 28. Implement strStr()
- LeetCode-28. Implement strStr()
- LeetCode *** 28. Implement strStr()
- Leetcode 28. Implement strStr()
- leetcode 28. Implement strStr() 实现strStr()函数
- Sunday算法的一种Java实现(Leetcode28. Implement strStr())
- Leetcode 28. Implement strStr() KMP算法解题
- [LeetCode] 28. Implement strStr() 实现strStr()函数