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

问题:给定一个字符串和一个子串,找到子串在字符串中出现的第一个索引位置,如果没有则返回-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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章