题目要求: 在子字符串中寻找目标字符串,并返回该字符串第一次出现时的下标

在尝试的写了一提中等难度的题目后,又一次回到简单难度的题寻找温暖T-T

思路一

在原字符串中中寻找目标字符串首字母的下标,并提取子字符串,若该字符串的开头等于目标字符串,则返回该下标
优点:速度相对较快
缺点:深度依赖api

public int strStr(String haystack, String needle) {
        int haystackLength = haystack.length();
        int needleLength = needle.length();
        if(haystackLength<needleLength){
            return -1;
        }else if(needleLength==0){
            return 0;
        }
        char start = needle.charAt(0);
        int index = haystack.indexOf(start);
        while(index!=-1){
            if(index+needleLength>haystackLength){
                index = -1;
                break;
            }
            if(haystack.substring(index).startsWith(needle)){
                break;
            }
            int tempIndex = haystack.substring(index+1).indexOf(start);
            index = tempIndex==-1?-1:(tempIndex+index+1);
        }
        return index;
    }

思路二

提取当前下标的子字符串并判断开头是否相等,相等则返回该下标

    public int strStr2(String haystack, String needle){
        int index = 0;
        for( ; index+needle.length()<=haystack.length() ; index++){
            if(haystack.substring(index).startsWith(needle)){
            //if(haystack.substring(index, index+needle.length).equals(needle){
                return index;
            }
        }
        if(index+needle.length()==haystack.length()){
            index = -1;
        }
        return index;
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行