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
给两个字符串,haystack和needle,找出haystack中第一次出现needle的索引位置,如果haystack中不存在needle,那么就返回-1.
思路:直接可以调用Sting类的indexOf(String str)
;这个方法,因为具有重载方法,所以一定要选对重载的方法。该方法就是返回在字符串中第一次出现子字符串的位置索引。
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 37.4 MB, less than 83.90% of Java online submissions for Implement strStr().
别人的实现:
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
}
Runtime: 4 ms, faster than 62.81% of Java online submissions for Implement strStr().
Memory Usage: 38.2 MB, less than 59.53% of Java online submissions for Implement strStr().
别人的手动实现:
1.判断是否为空,为空返回-1
2.不为空情况下开始循环,循环次数为haystack的长度-1,
3.用一个变量来记录第一次出现的匹配字符串的位置
4.该值要小于子字符串长度并且从匹配到的第一个字符的位置开始,两个字符串开始同步匹配,直到匹配结束,如果有不匹配的值,则返回-1.
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null)
return -1;
int l1 = haystack.length();
int l2 = needle.length();
for (int i = 0; i < l1-l2+1; i++) {
int count = 0;
while (count < l2 && haystack.charAt(i+count) == needle.charAt(count))
count++;
if (count == l2)
return i;
}
return -1;
}
}
Runtime: 1 ms, faster than 99.21% of Java online submissions for Implement strStr().
Memory Usage: 38.6 MB, less than 23.33% of Java online submissions for Implement strStr().
Next challenges: