LF.85.Determine If One String Is Another's Substring

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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     }

 

以上是关于LF.85.Determine If One String Is Another's Substring的主要内容,如果未能解决你的问题,请参考以下文章

js中if条件语句以及switch条件语句的使用

python day one 变量,if

python one liner建议简单的If语句[重复]

All-one Matrices

verilog中用if语句替换case D idea: one: two: three: end case

codeforces1276AAs Simple as One and Two