1. 程式人生 > >兩個字串中重複字串的最大連續長度

兩個字串中重複字串的最大連續長度

對比兩個字串中,重複字串的最大連續長度
  如: 
  string m_strA = "lgdglfsdafpganecw";
  string m_strB = "gogsspganklnleaf";
  最大公共字串為 pgan 長度為4
 private int GetMaxCommonStringCount(string strA, string strB)
    {
        int strLong = 0;
        if (string.IsNullOrEmpty(strA) || string.IsNullOrEmpty(strB))
            return strLong;

        string shortStr = "";
        string longStr = "";
        if (strA.Length > strB.Length)
        {
            shortStr = strB;
            longStr = strA;
        }
        else
        {
            shortStr = strA;
            longStr = strB;
        }

        int startIdx = 0;
        int endIndex = 0;

        for (int i = 0; i < shortStr.Length; i++)
        {
            //從短的字串開始,獲取每一次的固定對比長度,並且長度逐漸遞減
            startIdx = 0;
            endIndex = shortStr.Length - i;
            int fixlength = endIndex;

            while (endIndex <= shortStr.Length)
            {
                //按固定長度,輪詢獲取較短字串中的字串作為對比串,與長字串對比
                string comparaStr = shortStr.Substring(startIdx, fixlength);

                if (longStr.Contains(comparaStr))
                {
                    strLong = comparaStr.Length;
                    Debug.Log(comparaStr);
                    return strLong;
                }

                //按上面的固定長度輪詢
                startIdx = startIdx + 1;
                endIndex = endIndex + 1;
            }
        }

        return strLong;
    }