标签:bst nbsp com highlight string aaa index png hello
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,不知道为什么

标签:bst nbsp com highlight string aaa index png hello
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10153583.html