-
Notifications
You must be signed in to change notification settings - Fork 4
/
ImplementStrStr.java
45 lines (36 loc) · 950 Bytes
/
ImplementStrStr.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
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
*/
class Solution {
public int strStr(String haystack, String needle)
{
int needleLength = needle.length();
int hayLength = haystack.length();
if (needleLength > hayLength)
{
return -1;
}
if (needleLength == 0)
{
return 0;
}
for (int i = 0; i <= hayLength - needleLength; i++)
{
for (int j = 0; j < needleLength && haystack.charAt(i + j) == needle.charAt(j); j++)
{
if (j == needleLength - 1)
{
return i;
}
}
}
return -1;
}
}