字符串算法——字符串匹配

问题:给定一个字符串和一个子串,找到子串在字符串中出现的第一个索引位置,如果没有则返回-1.
解决思路:如果考虑到时间复杂度,则可以采用KMP算法,时间复杂度为 O(m+n) ,暂不详细介绍其原理过程。

class Solution {
    public int strStr(String haystack, String needle) {
       //KMP算法
        int len1 = haystack.length();//字符串长度
        int len2 = needle.length();//子串长度
        //判断二者大小
        if(len1 < len2){
            return -1;
        }
        if(len2 == 0){
            return 0;
        }
        int []next=getNext(needle);//获得子串的匹配模式表
        int j = 0;
        for(int i = 0;i<len1;i++){
            while(j>0 && haystack.charAt(i)!=needle.charAt(j)){
                j = next[j];
            }
            if (haystack.charAt(i) == needle.charAt(j))  
                j++;  
            if (j == len2) { 
                return i-j+1;
            }
        }
        return -1;
    }


    //匹配模式表
    public static int[] getNext(String s){
        int j = 0;
        int len = s.length();//子串长度
        int next[] = new int[len+1];//序号从1开始
        next[0] = next[1] = 0;//第一个元素匹配个数为0
        for(int i =1;i<len;i++){
            while(j>0 && s.charAt(i)!=s.charAt(j)){
                j = next[j];
            }
            if(s.charAt(i)==s.charAt(j))j++;
            next[i+1] = j;
        }
        return next;
    }
}

如果不考虑时间复杂度,可以将二者的字符元素依次比较,来找到索引,判断字符是否匹配。

//传统的字符串匹配,算法复杂度为O(N*M)
public class Solution {
    public int strStr(String haystack, String needle) {
        int l1 = haystack.length(), l2 = needle.length();
        if (l1 < l2) {
            return -1;
        } else if (l2 == 0) {
            return 0;
        }
        int threshold = l1 - l2;
        for (int i = 0; i <= threshold; ++i) {
            if (haystack.substring(i,i+l2).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值