字符串大小写规则排序

输入BadbAbB,输出AaBBbbd。因为A的ascii码比a小,所以相等的时候,直接输出a<b。不相等的时候,如果一个是大写,一个是小写,就要转换之后再比较。

 

复制代码
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <unordered_map>
using namespace std;

bool is_lower(char c)
{
    return c >= 'a' && c <= 'z';
}

static bool cmp(char& a, char& b)
{
    //保持a是小的,b是大的
    //考虑两种相同值
    if (a == b)
    {
        return a < b;
    }
    else if (abs(a - b) == 32)
    {
        //A的ascii码比较小,所以要放左边
        return a < b;
    }
    //考虑不同值的时候
    else
    {
        if (is_lower(a) && is_lower(b)) return a < b;
        else if (is_lower(a))
        {
            //b是大写
            char temp = b + 32;
            return a < temp; //返回a和b转换后的temp比较小的那个
            
        }
        else if (is_lower(b))
        {
            //a是大写
            char temp = a + 32;
            return temp < b; //返回b和a转换后的temp比较小的那个
        }
        else
        {
            return a < b; //两个都是大写的,返回比较小的那个
        }
    }
}

int main()
{
    string input = "BadbAbB";
    sort(input.begin(), input.end(), &cmp);
    cout << input << endl;
    //cout << 'A' - 'a' << endl;//-32,那么就是A的ascii数值比较小
    return 0;
}
复制代码

 今天面试的时候中间写了一个小bug。。。。

posted @   花与不易  阅读(125)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示