回文判断
参考:http://zhedahht.blog.163.com/
- 判断一个字串是否是回文。
- 输入一个字符串,输出该字符串中最长的回文子字符串的长度。
1、思路:
只要从两头开始同时向中间扫描字串,如果直到相遇两端的字符都一样,那么这个字串就是一个回文。我们只需要维护头部和尾部两个扫描指针即可;另一种方法是从中间开始、向两边扩展查看字符是否相等。
2、思路:
遍历字符串,对每一个字符往两边扩展,看两侧的字符是否相同,这样时间复杂度是O(n2)。注意扩展时考虑奇数和偶数两种情况。
GetLongestSymmetricalLength
1 int GetLongestSymmetricalLength_2(char* pString) 2 { 3 if(pString == NULL) 4 return 0; 5 6 int symmeticalLength = 1; 7 8 char* pChar = pString; 9 while(*pChar != '\0') 10 { 11 // Substrings with odd length 12 char* pFirst = pChar - 1; 13 char* pLast = pChar + 1; 14 while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast) 15 { 16 pFirst--; 17 pLast++; 18 } 19 20 int newLength = pLast - pFirst - 1; 21 if(newLength > symmeticalLength) 22 symmeticalLength = newLength; 23 24 // Substrings with even length 25 pFirst = pChar; 26 pLast = pChar + 1; 27 while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast) 28 { 29 pFirst--; 30 pLast++; 31 } 32 33 newLength = pLast - pFirst - 1; 34 if(newLength > symmeticalLength) 35 symmeticalLength = newLength; 36 37 pChar++; 38 } 39 40 return symmeticalLength; 41 }