-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathImplementStrStr.java
More file actions
71 lines (63 loc) · 2.13 KB
/
Copy pathImplementStrStr.java
File metadata and controls
71 lines (63 loc) · 2.13 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package Strings.implementStrStr;
/*
* 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().
* */
public class ImplementStrStr {
public static void main (String[] args){
String haystack = "Hello";
String needle = "lo";
int strStr = strStr(haystack, needle);
System.out.println(strStr);
}
public static int strStr(String haystack, String needle) {
/*
* If haystack is null
* or
* if needle is null
* or
* if the haystack string is shorter than the needle string
* Return -1 */
if(haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
/*
* If the needle string is empty, return 0
* */
if(needle.equals("")){
return 0;
}
/*
* Traverse through the haystack string */
for(int currentIndex = 0; currentIndex < haystack.length() - needle.length() + 1; currentIndex++){
// If the character at the current index equals the character at the first needle index
if(haystack.charAt(currentIndex) == needle.charAt(0))
/*
* check to see if the substring at the current index in the haystack */
if(haystack.substring(currentIndex, needle.length() + currentIndex).equals(needle))
// return the current index
return currentIndex;
}
// Otherwise return -1
return -1;
}
/*
* Complexity analysis
* Time Complexity: O(N + M) where N and M are the haystack and needle strings
* Space Complexity: O(1)
* */
}