Chapter 1 Calf Flac

来源:互联网 发布:苹果mac强制退出 编辑:程序博客网 时间:2024/06/05 15:55

Calf Flac

It is said that if you give an infinite number of cows an infinite number of heavy-duty laptops (with very large keys), that they will ultimately produce all the world's great palindromes. Your job will be to detect these bovine beauties.

Ignore punctuation, whitespace, numbers, and case when testing for palindromes, but keep these extra characters around so that you can print them out as the answer; just consider the letters `A-Z' and `a-z'.

Find any largest palindrome in a string no more than 20,000 characters long. The largest palindrome is guaranteed to be at most 2,000 characters long before whitespace and punctuation are removed.

PROGRAM NAME: calfflac
INPUT FORMAT
A file with no more than 20,000 characters. The file has one or more lines. No line is longer than 80 characters (not counting the newline at the end).
SAMPLE INPUT (file calfflac.in)
Confucius say: Madam, I'm Adam.
OUTPUT FORMAT

The first line of the output should be the length of the longest palindrome found. The next line or lines should be the actual text of the palindrome (without any surrounding white space or punctuation but with all other characters) printed on a line (or more than one line if newlines are included in the palindromic text). If there are multiple palindromes of longest length, output the one that appears first.

SAMPLE OUTPUT (file calfflac.out)
11Madam, I'm Adam

      其实这道题算不上什么有什么问题,但由于最近在了解C语言的一些东西,所以在写的时候了很多要注意的地方,现记录下来。

      首先,单就我第一次写这道题所用的方法(当然,可能有更好的方法),有一点要注意,在进行回文判断时,要选取每个点为回文中心,但是,要分为两种情况,一种就是回文序列是偶数长度,另一种就是奇数。两种情况的最大不同就在与回文中心的字符数量,奇数的只有一个字符,偶数的有两个字符。

check_oddvoid check_odd(char *str,int num,int *max,char *str_pal){    int i=num,j=num;    int len=strlen(str);    do    {        while (!((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))&& i>=0) i—-;//无视非字母字符        while (!((str[j]>='a'&&str[j]<='z')||(str[j]>='A'&&str[j]<='Z'))&& j//同上        if (0==str[i]-str[j] || 32==str[i]-str[j] || -32==str[i]-str[j])//判断两字符是否相同,即ASCII相同或差的绝对值为32(大小写之差)        {            if (j-i+1>*max)//更新记录            {                *max=j-i+1;                strncpy(str_pal,str+i,*max);                str_pal[*max]='/0';            }            i--;            j++;        }        else break;    }while (i>-1 && j

check_even与odd类似,只是初始的i、j的初值换为

int i=num,j=num+1;
要注意的是,在更新max和str_pal的时候,由于strnpy()不会在字符串尾自动补上
'/0'
的,所以在更新完毕后要手动补上,并且结束符是字符不是字符串,要用单引号。
 
关于哪些函数会自动补0哪些不会,还要进一步总结。