LeetCode-Implement strStr()
2015-02-04 10:21
330 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解答
开始写的代码竟然超时
之后做了简单的优化,把最外层循环的迭代降低了,如下:
这个竟然AC了,也是醉了。。。
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解答
开始写的代码竟然超时
public int strStr(String haystack, String needle) { if (haystack == null || needle == null || haystack.length() < needle.length()) return -1; if (needle.equals("")) { return 0; } int i = 0, j = 0, index = -1, k; while (i < haystack.length()) { if (haystack.charAt(i) == needle.charAt(0)) { index = i; for (j = 0, k = i; j < needle.length() && k < needle.length(); j++, k++) { if(haystack.charAt(k) != needle.charAt(j)) break; } } if (j == needle.length()) { return index; } i++; } return -1; }
之后做了简单的优化,把最外层循环的迭代降低了,如下:
public int strStr(String haystack, String needle) { if (haystack == null || needle == null || haystack.length() < needle.length()) return -1; if (needle.equals("")) { return 0; } int i = 0, j = 0, index = -1, k; while (i < haystack.length()-needle.length()+1) { if (haystack.charAt(i) == needle.charAt(0)) { index = i; for (j = 0, k = i; j < needle.length(); j++, k++) { if(haystack.charAt(k) != needle.charAt(j)) break; } } if (j == needle.length()) { return index; } i++; } return -1; }
这个竟然AC了,也是醉了。。。
相关文章推荐
- [LeetCode] Implement strstr() to Find a Substring in a String
- LeetCode 28 Implement strStr()(子字符串查找)
- LeetCode Implement strStr()
- [LeetCode] Implement strStr()
- (leetcode) Implement strStr()
- LeetCode(28) Implement strStr()
- Leetcode Implement strStr()解题报告
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- [LeetCode] 034: Implement strStr()
- LeetCode之Implement strStr()
- LeetCode Implement strStr()
- leetcode - Implement strStr()
- 【LeetCode】028.Implement strStr()
- LeetCode:Implement strStr()
- LeetCode | Implement strStr()
- 【LeetCode 28_字符串_匹配】Implement strStr()
- Leetcode Implement strStr()
- LeetCode: Implement strStr()
- [leetcode] Implement strStr()
- C++ 写leetcode遇到的一些问题总结Implement strStr()