题目:28. Implement strStr() 实现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().
题意解析:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
解题思路一:
先对两个字符串的长度进行判断。之后我们就可以利用字符串的substring函数依次让右边的字符串去左边匹配,注意这里的长度只有左边的长度减去右边的长度的长度。
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;
}
提交代码之后:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 36.7 MB, less than 98.46% of Java online submissions for Implement strStr().