忽略大小写的字符串比较

GitHub跳转原题关系图返回列表

将两行字符串统一转小写后,按字典序直接比较大小。

OJ: noi_openjudge

题目 ID: ch0107-16

难度:入门

标签:字符串比较python

日期: 2026-07-30 23:01

题意

忽略字母大小写,比较两行字符串的字典序并输出 <>=

思路

先对两串调用 lower() 消除大小写差异,Python 的字符串比较会按字典序完成逐字符比较。

代码

Python代码

python
first = input().lower()
second = input().lower()

if first < second:
    print("<")
elif first > second:
    print(">")
else:
    print("=")

C++代码

cpp
#include <cstdio>
#include <cstring>

char str1[500];
char str2[500];
int idx1=0;
int idx2=0;
int main(){
    char t;
    while(1){
        int ret = scanf("%c",&t);
        if( t == '\n' || t == '\r' || ret == EOF)
            break;
        if( t >='A' && t <='Z') t = t+'a'-'A';
        str1[++idx1] = t;
    }
    while(1){
        int ret = scanf("%c",&t);
        if( t == '\n' || t==  '\r')
            continue;
        if( t >='A' && t <='Z') t = t+'a'-'A';
        str2[++idx2] = t;
        break;
    }

    while(1){
        int ret = scanf("%c",&t);
        if( t == '\n' || t == '\r' || ret == EOF)
            break;
        if( t >='A' && t <='Z') t = t+'a'-'A';
        str2[++idx2] = t;
    }
    int ans =  strcmp(str1+1,str2+1);
    if( ans == 0)
        printf("=");
    else if(ans < 0 )
        printf("<");
    else 
        printf(">");
    return 0;
}

复杂度

设较长字符串长度为 nn,时间复杂度为 O(n)O(n),额外空间复杂度为 O(n)O(n)

总结

忽略大小写的比较先做统一规范化,再复用普通字符串比较。