-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT13.java
More file actions
44 lines (44 loc) · 1.31 KB
/
T13.java
File metadata and controls
44 lines (44 loc) · 1.31 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
public class T13 {
/*
* @param source: source string to be scanned.
* @param target: target string containing the sequence of characters to match
* @return: a index to the first occurrence of target in source, or -1 if target is not part of source.
*/
public int strStr(String source, String target) {
// write your code here
if (source == null || target == null) {
return -1;
}
if (source.length() == 0 && target.length() == 0) {
return 0;
}
if (source.length() == 0) {
return -1;
}
if (target.length() == 0) {
return -0;
}
char[] sou = source.toCharArray();
char[] tar = target.toCharArray();
if (source.length() == target.length()) {
for (int i = 0; i < sou.length ; i++) {
if (sou[i] != tar[i]) {
return -1;
}
}
return 0;
}
for (int i = 0; i <= sou.length - tar.length; i++) {
int j;
for (j = 0; j < tar.length; j++) {
if (sou[i+j] != tar[j]) {
break;
}
}
if (j == tar.length) {
return i;
}
}
return -1;
}
}