题目地址
https://leetcode.com/problems/implement-strstr/description/
题目描述
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().
思路
- for循环即可. i在source中移动, j在target中移动. 如果source中在i+j位置的char不等于target中在j位置的char. i++, 开始下一轮计算.
- 如果j已经等于target的length, 说明已经找到了. 返回i即可.
- 注意边界条件, 如果一直没找到, return -1.
关键点
- for循环从0到haystack.length() - needle.length() + 1.
代码
- 语言支持:Java
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
for (int i = 0; i < haystack.length() - needle.length() + 1; 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;
}
}
网友评论