Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
public int strStr(String haystack, String needle) {
int l1=haystack.length();
int l2=needle.length();
if(l1<l2)
{
return -1;
}
else if(l2==0)
{
return 0;
}
for(int i=0;i<=l1-l2;i++)
{
if(haystack.substring(i,i+l2).equals(needle))
{
return i;
}
}
return -1;
}
class Solution {
public int strStr(String haystack, String needle) {
int l1 = haystack.length();
int l2 = needle.length();
if (l1 < l2) {
return -1;
} else if (l2 == 0) {
return 0;
} else {
for (int i = 0; i <= l1 - l2; i++) {
boolean found = true; //先預設為true
for (int j = 0; j < l2; j++) { //找接下來字母有無相同
if (haystack.charAt(i+j) != needle.charAt(j)){
found =false;
break;
}
}
if (found){
return i;
}
}
}
return -1;
}
}