• 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     }
  • 相关阅读:
    let 及const
    ES6与ES2015、ES2016以及ECMAScript的区别
    AMD CMD commonJS es6
    千里之行,始于足下
    学习随笔 pyspark JDBC 操作oracle数据库
    学习随笔--pyspark RDD常用操作
    学习随笔--Spark java开发入门
    学习随笔--flask框架基本搭建
    学习随笔--scrapy爬虫简单实例
    学习随笔-python动态爬取空气质量网数据的实现
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8726633.html
Copyright © 2020-2023  润新知