题目来源:https://leetcode.com/problems/longest-palindromic-substring/#/description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
我的C程序:
int get_longest_str_len(char *s, int li, int ri, int len)
{
int maxlen = 0;
for (; li>=0&&ri<len; li--,ri++)
{
if (s[li] == s[ri])
{
maxlen+=2;
}
else
{
break;
}
}
return maxlen;
}
char* longestPalindrome(char* s)
{
int len = strlen(s);
int li,ri,index,i,maxindex=0,currlen=0,maxlen=1;//没有回文时,一个字母也是
char *longeststr = NULL;
if (len == 1 || (len==2 && s[0] == s[1]))
{
return s;
}
for (i=1; i<len-1; i++)
{
if (s[i-1] == s[i])
{
currlen = get_longest_str_len(s, i-1, i, len);
if (s[i] == s[i+1])//考虑abbba这种情况
{
int templen = 1+get_longest_str_len(s, i-1, i+1, len);
currlen = templen>currlen?templen:currlen;
}
index = i-(currlen/2);
}
else if(s[i] == s[i+1])
{
currlen = get_longest_str_len(s, i, i+1, len);
index = i-(currlen/2)+1;
}
else if (s[i-1] == s[i+1])
{
currlen = 1 + get_longest_str_len(s, i-1, i+1, len);
index = i-(currlen/2);
}
if (currlen > maxlen)
{
maxlen = currlen;
maxindex = index;
}
}
if (maxlen > 0)
{
longeststr = (char *)calloc(maxlen+1, 1);//分配相应的空间并清零
memcpy(longeststr, s+maxindex, maxlen);
}
return longeststr;
}
过程与思路:中间有很多的情况没有考虑到,比如aaaa以及abbba这样的字串。思路主要是考虑回文的特性是由中间的字母往两边扩散是对应相等的,
由此检索所有的回文长度,记录最长的长度和起始位置,字符串检测结束后,再分配相应空间复制。
结论:由图可以看出程序直接的性能差异很大,而看自己的程序,一点没有美感,测试N次才通过,写一点想一点,不能提前思考好整个过程,程序思维能力相当差。同时也证明了测试的重要,人是很难考虑到很全面的各种可能性的,也可见白盒测试真是个不简单的工作。