-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementstrStr.java
More file actions
33 lines (30 loc) · 970 Bytes
/
ImplementstrStr.java
File metadata and controls
33 lines (30 loc) · 970 Bytes
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
/*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
import java.util.*;
public class ImplementstrStr {
public static int strStr(String haystack, String needle) {
if(needle.length() > haystack.length()) return -1;
if(needle.length() == 0) return 0;
for(int i = 0; i <= haystack.length()-needle.length(); i++){
boolean e = true;
for(int j = 0; j < needle.length(); j++){
if(needle.charAt(j) != haystack.charAt(i+j)) e = false;
}
if(e == true){
return i;
}
}
return -1;
}
public static void main(String[] args) {
String s = "abcddwdw";
String t = "cdd";
int res = strStr(s, t);
System.out.println("Source string: " + s);
System.out.println("Taregt string: " + t);
System.out.println("first occurrence position: " + res);
return;
}
}