LeetCode笔记:28. Implement strStr()
2016-12-10 16:33
369 查看
问题:
Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
大意:
实现 strStr()。返回 haystack 中第一次出现 needle 的位置,如果 needle 不是 haystack 的一部分则返回 -1。
思路:
最简单的做法就是遍历 haystack ,发现和 needle 第一个字符相同的元素,就开始逐个比较,如果全部比完发现一样,那么返回之前那个开始位置就可以了,如果中途有不一样的,那么就要从之前的位置的下一个位置开始继续遍历寻找。代码(Java):
public class Solution { public int strStr(String haystack, String needle) { if (needle.equals("")) return 0; char[] haystackArr = haystack.toCharArray(); char[] needleArr = needle.toCharArray(); int i = 0; int j = 0; for (; i < haystackArr.length;i++) { if (haystackArr[i] == needleArr[j]) { for (int k = i; k < haystackArr.length && j < needleArr.length; k++, j++) { if (haystackArr[k] != needleArr[j]) break; } if (j == needleArr.length) return i; else j = 0; } } return -1; } }
他山之石:
public class Solution { public int strStr(String haystack, String needle) { int l1 = haystack.length(), l2 = needle.length(); if (l1 < l2) { return -1; } else if (l2 == 0) { return 0; } int threshold = l1 - l2; for (int i = 0; i <= threshold; ++i) { if (haystack.substring(i,i+l2).equals(needle)) { return i; } } return -1; } }
之前的做法耗时很长,因为遇到一样的之后都要进行逐个比较。这个做法就比较简单了,先把集中特殊情况处理了,然后直接比较子字符串是否相等,除去了单个字符比较的麻烦,时间省了很多。
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
相关文章推荐
- 小白笔记-----------------------leetcode(28. Implement strStr())
- LeetCode --- 28. Implement strStr()
- 【leetcode】28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr()
- 28. Implement strStr()-leetcode-java
- 【LeetCode】28. Implement strStr() (2 solutions)
- 【leetcode】28. Implement strStr()
- Leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- 【LeetCode】28. Implement strStr()
- <LeetCode OJ> 28. Implement strStr()
- [leetcode] 28. Implement strStr() 解题报告
- LeetCode *** 28. Implement strStr()
- [Leetcode] 28. Implement strStr()
- [LeetCode] 28. Implement strStr() 解题思路
- 28. Implement strStr() LeetCode
- 【一天一道LeetCode】#28. Implement strStr()
- Leetcode 28. Implement strStr() KMP算法解题