LeetCode-- Implement strStr()
2017-09-24 11:51
357 查看
题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解读:給字符串haystack和字符串needle,找到haystack中第一次出现needle的位置下标并返回。
代码:class Solution {
public int strStr(String haystack, String needle) {
int len_1 = haystack.length();
int len_2 = needle.length();
if(len_2 == 0) return 0;
if(len_1<len_2) return -1;
for(int i = 0; i < len_1; i++) {
if(i + len_2 -1 >= len_1)
return -1;
else {
String temp = haystack.substring(i, i+len_2);
if(needle.equals(temp)) return i;
}
}
return -1;
}
}
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解读:給字符串haystack和字符串needle,找到haystack中第一次出现needle的位置下标并返回。
代码:class Solution {
public int strStr(String haystack, String needle) {
int len_1 = haystack.length();
int len_2 = needle.length();
if(len_2 == 0) return 0;
if(len_1<len_2) return -1;
for(int i = 0; i < len_1; i++) {
if(i + len_2 -1 >= len_1)
return -1;
else {
String temp = haystack.substring(i, i+len_2);
if(needle.equals(temp)) return i;
}
}
return -1;
}
}
相关文章推荐
- 【leetcode】Implement strStr() (easy)
- Leetcode-Implement strStr()
- LeetCode Implement strStr(kmp或者BM)
- [Leetcode][python]Implement strStr()/KMP算法
- leetcode Implement strStr()
- LeetCode(28)题解:Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- LeetCode 028. Implement strStr()
- [leetcode]Implement strStr()
- LeetCode Implement strStr()
- [leetcode]Implement strStr()
- [LeetCode] Implement strStr()[字符串hash]
- LeetCode | Implement strStr()
- [leetcode]Implement strStr()
- [LeetCode] Implement strStr()
- [Leetcode] #28 Implement strStr()
- [Leetcode]_28 Implement strStr()
- [C++]LeetCode: 27 Implement strStr()
- leetcode - Implement strStr()