两个字符串中重复字符串的最大连续长度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sam_ONE/article/details/83792245
对比两个字符串中,重复字符串的最大连续长度
  如: 
  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;
    }

猜你喜欢

转载自blog.csdn.net/Sam_ONE/article/details/83792245