LeetCode 28 实现strStr()

题目描述:
题目描述




方法一(暴力匹配):
从长字符串中取第一个字符与短字符串第一个字符比较,相等比较各自的下一个字符,直到不相等,如果此时匹配相等长度比短字符串小,则第一次没有找到,进行第二次,从长字符串取第二个字符与短字符串第一个字符比较,以此类推,直至长字符串比较完,或者比较完前找到等于短字符串的子串。

代码(Java实现):

class Solution {
    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0){//字符串为空,返回0
            return 0;
        }
        
        char[] hs = haystack.toCharArray();
        char[] nd = needle.toCharArray();
        int h = 0;//haystack字符串中的索引
        while(h < haystack.length() - needle.length() +1){//while要满足的大条件
            while(h < haystack.length() - needle.length() +1 && hs[h] != nd[0]){//找到与needle字符串第一个字符相等的haystack的字符索引
                   h++;
           }

            int n = 0;
            int count = 0;

            while(n < needle.length() && h < haystack.length() && hs[h] == nd[n]){//比较字符,同时记录相等的字符个数count
                    h++;
                    n++;
                    count++;
            }

            if(count == needle.length()){//如果count等于needle的长度,说明找到了,返回与needle第一个字符相等的haystack中字符的索引
                return h - count;
            }

            h = h - count +1;//小于的话,回到之前paystack部分匹配的字符串的第二个索引,继续进行比较
       }
       return -1;//没找到返回-1
    }
}

结果:
结果


代码(C语言):

int strStr(char * haystack, char * needle){
    int hslen = strlen(haystack);
    int ndlen = strlen(needle);

    if(ndlen == 0){
        return 0;
    }
    for(int i = 0;i < hslen;i++){
        if(hslen - i < ndlen){
            return -1;
        }

        int n = i,m = 0;

        while(m < ndlen && n < hslen && haystack[n] == needle[m]){
            if(m == ndlen -1){
                return i;
            }
            m++;
            n++;
        }
    }
    return -1;
}

结果:
结果



方法二(分割子串匹配):
从长字符第一个字符开始分割出长度为短字符串长度的子串与短字符串比较,不相等,则取长字符串第二个字符开始的长度为短字符串长度的子串,直至长字符串比较完,或者成功找到匹配的子串。

代码(Java实现):

class Solution {
    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0){
            return 0;
        }
        
        int hslen = haystack.length(),ndlen = needle.length();

        for(int i = 0;i < hslen - ndlen + 1;i++){
            if(haystack.substring(i,i+ndlen).equals(needle)){//灵活运用分割字符串的substring方法,来匹配needle字符串
                return i;
            }
        }
        return -1;
    }
}

结果:
结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值