程序员面试题精选100题(46)-对称子字符串的最大长度

题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。

思路,把每个都看成是对称中心,然后向外扩展。。
int GetLongestSymmetricalLength_2(char* pString)
{
       if(pString == NULL)
              return 0;
       int symmeticalLength = 1;
       char* pChar = pString;
       while(*pChar != '\0')
       {
              // Substrings with odd lengt
              char* pFirst = pChar - 1;
              char* pLast = pChar + 1;
              while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast)
              {
                     pFirst--;
                     pLast++;
              }
              int newLength = pLast - pFirst - 1;
              if(newLength > symmeticalLength)
                     symmeticalLength = newLength;
              // Substrings with even length
              pFirst = pChar;
              pLast = pChar + 1;
              while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast)
              {
                     pFirst--;
                     pLast++;
              }
              newLength = pLast - pFirst - 1;
              if(newLength > symmeticalLength)
                     symmeticalLength = newLength;
              pChar++;
       }
       return symmeticalLength;
}

你可能感兴趣的:(数据结构)