28. 实现 strStr() Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1
if needle
is not part of haystack
.
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().
public int strStr(String haystack, String needle) { if( needle == null ) return 0; int m = haystack.length(), n = needle.length(); for(int i = 0; i < m - n + 1; i++){ if( haystack.substring(i, i + n).equals(needle)) return i; } return -1; }
参考链接:
https://leetcode.com/problems/implement-strstr/
https://leetcode-cn.com/problems/implement-strstr/