脚本宝典收集整理的这篇文章主要介绍了28. Implement strStr(),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Implement strStr().
Return the index of the First occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this PRoblem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
难度: easy
题目:
实现方法strstr()
返回首次needle出现在haystack中的索引,如果不存在则返回 -1.
Runtime: 7 ms, faster than 37.21% of Java online submissions for Implement strStr().
Memory usage: 26.9 MB, less than 32.93% of Java online submissions for Implement strStr().
class Solution { public int strStr(String haystack, String needle) { if (needle.length() > haystack.length()) { return -1; } for (int i = 0; i <= haystack.length() - needle.length(); i++) { int j = 0; for (; j < needle.length(); j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == needle.length()) { return i; } } return -1; } }
以上是脚本宝典为你收集整理的28. Implement strStr()全部内容,希望文章能够帮你解决28. Implement strStr()所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。