leetcode28 Implement strStr() 在字符串中寻找目标字符串

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

在尝试的写了一提中等难度的题目后,又一次回到简单难度的题寻找温暖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
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值