Leetcode : eImplement strStr

Leetcode : eImplement strStr

描述

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。

如果不让你采用正则表达式,你会怎么做呢?

思路:
1、 先排除source为null、target为null的情况
2、 如果target的length为0,则返回0
3、 如果target的length>source的length,则返回-1
4、 定义一个for循环遍历source字符串,循环比对target字符串
4.1、在for循环外部定义一个索引index,用来索引target,每一次循环,只有比对成功,index++;然后比对index和target的length长度,如果相同,则返回下标
4.2、当比对不成功时,index重新赋值为0;需要重新比对一下,source[i]和target[0]

好了,我们跟着思路来实现一下代码

public static int strstr(String source , String target ) {
    if(source == null || target == null ) {
        return -1;
    }
        
    int m = source.length();
    int n = target.length();
        
    if(n == 0) {
        return 0;
    }
        
    if(n > m ) {
        return -1;
    }
    int index = 0;
    for(int i = 0 ; i < m ; i++ ) {
        if( source.charAt(i) == target.charAt(index) ) {
            index++;
            if(index == n) {
                //index多加了一次
                return i - index + 1 ;
            }
        }else {
            index = 0;
            //source[i]需要和target[0]重新比对一下
            if( source.charAt(i) == target.charAt(index) ) {
                index++;
            }
        }
    }
    return -1;
}

补充:

《Leetcode : eImplement strStr》

所需知识:

List是有序(有序是指放入地顺序)的collection。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素地整数索引访问元素。

List通常允许有重复的元素;更确切地讲,List通常允许满足e1.equals(e2)的元素对,并且如果List本身允许null元素的话,通常它们允许多个null元素;List只是一个接口

Set是一个不包含重复元素的collection。更确切地讲,set不包含满足e1.equals(e2)的元素对,并且最多包含一个null元素

Set: HashSet(无序的),LinkedHashSet,TreeSet,EnumSet(后三个有序)

知道了这些,这题的答案明显就是A了

以后Leetcode系列的文章都是这种风格了,题+题;对java面试还是比较有用的……

    原文作者:奇迹迪
    原文地址: https://www.jianshu.com/p/beec49582ed4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞