第一篇链接:字符串类习题、面试题详解(第一篇)
6题:回文串(竞赛基础题)
输入一个字符串,求出其最长回文子串。子串的含义是:在原串中连续出现的字符串片段。回文的含义是:正着看和倒着看相同,如abba和yyxyy。在判断时,应该忽略所有标点符号和空格,且忽略大小写,但输出应保持原样(在回文串的首部和尾部不要输出多余字符)。输入字符串长度不超过5000,且占据单独一行。应该输出最长的回文串,如果有多个,输出起始位置最靠左的。
样例输入:Confuciuss say: Madam, I’m Adam.
样例输出:Madam,I’m Adam
方法1:枚举回文串的起点和终点。
1 #include <stdio.h> 2 #include <ctype.h> 3 #include <string.h> 4 #define MAXN 5000 + 10 5 6 char buf[MAXN], s[MAXN]; 7 int p[MAXN]; 8 9 int main(void) 10 { 11 int n, m = 0, max = 0, x = 0, y = 0; 12 int i, j, k, ok; 13 fgets(buf, sizeof(buf), stdin); 14 n = strlen(buf); 15 16 for (i = 0; i < n; i++) 17 { 18 if (isalpha(buf[i])) 19 { 20 p[m] = i; //保存字符的实际位置 21 s[m++] = toupper(buf[i]); //保存为大写字母 22 } 23 } 24 25 for (i = 0; i < m; i++) //枚举回文串起始位置 26 { 27 for (j = i; j < m; j++) //枚举回文串终止位置 28 { 29 ok = 1; 30 for (k = i; k <= j; k++) 31 { 32 if (s[k] != s[i + j - k]) 33 ok = 0; 34 } 35 36 if (ok && j - i + 1 > max) 37 { 38 max = j - i + 1; 39 x = p[i]; 40 y = p[j]; 41 } 42 } 43 } 44 45 for (i = x; i <= y; i++) 46 { 47 printf("%c", buf[i]); 48 } 49 printf(" "); 50 51 return 0; 52 }
方法2:枚举回文串的中间位置。
1 #include <stdio.h> 2 #include <string.h> 3 #include <ctype.h> 4 #define MAXN 5000 + 10 5 char buf[MAXN], s[MAXN]; 6 int p[MAXN]; 7 8 int main(void) 9 { 10 int n, m = 0, max = 0, x = 0, y = 0; 11 int i, j; 12 fgets(buf, sizeof(buf), stdin); 13 n = strlen(buf); 14 15 for (i = 0; i < n; i++) 16 { 17 if (isalpha(buf[i])) 18 { 19 p[m] = i; //保存字符实际位置 20 s[m++] = toupper(buf[i]); 21 } 22 } 23 24 for (i = 0; i < m; i++) //枚举回文串的中间位置 25 { 26 for (j = 0; i - j >= 0 && i + j < m; j++) //回文子串长度为奇数 27 { 28 if (s[i - j] != s[i + j]) 29 break; 30 if (j * 2 + 1 > max) 31 { 32 max = j * 2 + 1; 33 x = p[i - j]; 34 y = p[i + j]; 35 } 36 } 37 38 for (j = 0; i - j >= 0 && i + j + 1 < m; j++) //回文串长度为偶数 39 { 40 if (s[i - j] != s[i + j + 1]) 41 break; 42 if (j * 2 + 2 > max) 43 { 44 max = j * 2 + 2; 45 x = p[i - j]; 46 y = p[i + j + 1]; 47 } 48 } 49 } 50 51 for (i = x; i <= y; i++) 52 printf("%c", buf[i]); 53 printf(" "); 54 55 return 0; 56 }
解析:枚举回文串的中间位置时要注意长度为奇数和偶数的处理方式是不一样的。
7题:编码实现求给定字符串(全为小写英文字母)的最小后继,如"abc"的最小后继为"abd","dhz"的最小后继为"di"。(Google笔试题)
1 #include <stdio.h> 2 #include <string.h> 3 #define MAXN 1024 4 5 int main(void) 6 { 7 char buf[MAXN]; 8 int n, m, i; 9 scanf("%s", buf); 10 11 n = strlen(buf); 12 for (i = n - 1; i >= 0; i--) 13 { 14 if (buf[i] + 1 <= 'z') 15 { 16 buf[i] += 1; 17 buf[i + 1] = '