BF算法(蠻力匹配算法)

將主串M指定位置和目標串S開始位置進行對比,若是相同將M的下一個字符和S的下一個字符對比,若是不一樣則M的下一個字符和S的開始位置對比,直到S中每個字符和M中的連續字符串相等,不然不匹配。spa

C#代碼-->code

       private static int Index(string m,int  pos, string s)
        {
            int m_len = m.Length;
            int s_len = s.Length;
            int i = pos-1;
            int j = 0;
            if (pos>m_len)
            {
                return -1;
            }
            while ( i<m_len && j<s_len)
            {
                if (m[i]==s[j])
                {
                    i++;
                    j++;
                }
                else
                {
                    j = 0;
                    i = i - j + 1;
                }
            }
            if (j>=s_len)
            {
                return i - s_len;
            }
            else
            {
                return 0;
            }
        }


//調用
 int res = Index("asdfghjkl", 2, "fghjk");
 Console.WriteLine(res);

 複雜度爲O(M*N)blog

相關文章
相關標籤/搜索