LF.85.Determine If One String Is Another's Substring
Determine if a small string is a substring of another large string.
Return the index of the first occurrence of the small string in the large string.
Return -1 if the small string is not a substring of the large string.
Assumptions
Both large and small are not null
If small is empty string, return 0
Examples
“ab” is a substring of “bcabc”, return 2
“bcd” is not a substring of “bcabc”, return -1
"" is substring of "abc", return 0
1 public int strstr(String large, String small) {
2 // Write your solution here
3 if (large == null || small == null){
4 return -1 ;
5 }
6 if (large.length() == 0 && small.length() ==0 ){
7 return 0 ;
8 }
9 if (large.length() == 0){
10 return -1 ;
11 }
12
13 if (small.length() ==0){
14 return 0;
15 }
16
17 if (large.length() < small.length()){
18 return -1 ;
19 }
20 //loop through large and small
21 //if L != S break
22 /*
23 b c a b c
24 i
25 a b c
26 j
27 * */
28 for (int i = 0; i <= large.length() - small.length() ; i++) {
29 int j = 0 ;
30 for (; j < small.length(); j++) {
31 if (large.charAt(i+j) != small.charAt(j)){
32 //out of inner loop, increase the i
33 break;
34 }
35 }
36 //check to make sure only return when j reaches the end, otherwise when out of the break, will execute this line
37 if (j == small.length()){
38 return i ;
39 }
40 }
41 return -1 ;
42 }