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

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