28. Implement strStr()
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
笨方法1:
class Solution { public int strStr(String haystack, String needle) { if(needle==""||needle==null){ return 0; } else return haystack.indexOf(needle); } }
直接用indexOf
方法2:
class Solution { public int strStr(String haystack, String needle) { int res = 0; if(needle==""||needle==null){ return res; } else{ int n = needle.length(); int i = 0; for(; i< haystack.length()-n; i++){ if(haystack.substring(i,i+n).equals(needle)){ res = i; break; } } if(i>=haystack.length()-n){ res = -1; } } return res; } }
奇怪的是当输入为("","")时,leetcode会报错,但是eclipse输出还是0,不知道为什么
以上是关于28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 28. Implement strStr() 实现strStr()