字符串应用——回文拼接
任务描述
编写一个程序,判断给定的字符串是否由两个长度至少为2的回文串前后拼接而成。
输入输出要求
输入: 第一行包含一个正整数 n,代表字符串数量。之后 n 行每行一个仅包含小写字母的字符串。
输出: 对于每个字符串输出一行,如果该字符串由两个长度至少为2的回文串前后拼接而成则输出 "Yes",否则输出 "No"。
代码实现
cpp
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char ch[]) {
int len = strlen(ch);
for (int i = 0; i < len / 2; ++i) {
if (ch[i] != ch[len - 1 - i]) {
return false;
}
}
return true;
}
bool canBePalindromeConcatenated(char ch[]) {
int len = strlen(ch);
for (int i = 1; i < len - 1; ++i) {
if (isPalindrome(&ch[0]) && isPalindrome(&ch[i])) {
return true;
}
}
return false;
}
int main() {
int num;
scanf("%d", &num);
getchar(); // Consume the newline character
for (int i = 0; i < num; i++) {
char ch[100000];
fgets(ch, sizeof(ch), stdin);
ch[strcspn(ch, "\n")] = 0; // Remove the newline character
if (canBePalindromeConcatenated(ch)) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
}
总结
代码实现了对字符串的回文判断和拼接判断。通过这次练习,我加深了对字符串操作和循环控制的理解。同时,我也意识到在编写代码时,清晰的逻辑和良好的代码风格是非常重要的。
编写一个程序,判断给定的字符串是否由两个长度至少为2的回文串前后拼接而成。
输入输出要求
输入: 第一行包含一个正整数 n,代表字符串数量。之后 n 行每行一个仅包含小写字母的字符串。
输出: 对于每个字符串输出一行,如果该字符串由两个长度至少为2的回文串前后拼接而成则输出 "Yes",否则输出 "No"。
代码实现
cpp
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char ch[]) {
int len = strlen(ch);
for (int i = 0; i < len / 2; ++i) {
if (ch[i] != ch[len - 1 - i]) {
return false;
}
}
return true;
}
bool canBePalindromeConcatenated(char ch[]) {
int len = strlen(ch);
for (int i = 1; i < len - 1; ++i) {
if (isPalindrome(&ch[0]) && isPalindrome(&ch[i])) {
return true;
}
}
return false;
}
int main() {
int num;
scanf("%d", &num);
getchar(); // Consume the newline character
for (int i = 0; i < num; i++) {
char ch[100000];
fgets(ch, sizeof(ch), stdin);
ch[strcspn(ch, "\n")] = 0; // Remove the newline character
if (canBePalindromeConcatenated(ch)) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
}
总结
代码实现了对字符串的回文判断和拼接判断。通过这次练习,我加深了对字符串操作和循环控制的理解。同时,我也意识到在编写代码时,清晰的逻辑和良好的代码风格是非常重要的。
全部评论
相关推荐
点赞 评论 收藏
分享
03-06 14:58
电子科技大学 算法工程师 点赞 评论 收藏
分享
点赞 评论 收藏
分享