删除空格并统一转小写后,比较两行字符串是否相等。
OJ: noi_openjudge
题目 ID: ch0107-17
难度:入门
标签:字符串比较python
日期: 2026-07-30 23:01
题意
判断两行只含字母和空格的字符串在忽略大小写与空格后是否相等。
思路
每行先用 replace(" ", "") 删除空格,再调用 lower(),比较规范化后的两个结果。
代码
Python代码
python
first = input().replace(" ", "").lower()
second = input().replace(" ", "").lower()
print("YES" if first == second else "NO")C++代码
cpp
#include <cstdio>
#include <cstring>
char content[2000];
char str1[1000];
char str2[1000];
int idx1=0;
int idx2=0;
int main(){
char t;
// 读取所有的内容
while( scanf("%c",&t) != EOF){
content[++idx1]= t;
}
idx1 = 0;
int all_len = strlen(content+1);
int i,j=0;
for (i=1;i<=all_len;i++){
char c = content[i];
if( c == '\n' || c == '\r')
break;
else if(c != ' ') {
if( c >='A' && c <='Z')
str1[++j] = c+'a'-'A';
else
str1[++j] = c;
}
}
str1[j] ='\0';
// 略过剩下的 \n \r
for(;1;i++){
if( content[i] == '\n' || content[i] == '\r' )
;
else
break;
}
j=0;
for(;i<=all_len;i++){
char c = content[i];
if( c == '\n' || c == '\r')
break;
else if(c != ' ') {
if( c >='A' && c <='Z')
str2[++j] = c+'a'-'A';
else
str2[++j] = c;
}
}
str2[j] = '\0';
int ans = strcmp(str1,str2);
if( ans == 0)
printf("YES");
else
printf("NO");
return 0;
}复杂度
设总输入长度为
总结
多个“忽略规则”可依次规范化,再做一次普通相等比较。