Leetcode 1507. 转变日期格式
Published on 2022-05-14 12:23 in 分类: C/C++ with 萧海~
分类: C/C++

Leetcode 1507. 转变日期格式

    在这里插入图片描述
    给你一个字符串 date ,它的格式为 Day Month Year ,其中:

    • Day 是集合 {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} 中的一个元素。
    • Month 是集合 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
      "Sep", "Oct", "Nov", "Dec"} 中的一个元素。
    • Year 的范围在 ​[1900, 2100] 之间。

    请你将字符串转变为 YYYY-MM-DD 的格式,其中:

    • YYYY 表示 4 位的年份。
    • MM 表示 2 位的月份。
    • DD 表示 2 位的天数。

    示例 1:

    输入:date = "20th Oct 2052"
    输出:"2052-10-20"

    示例 2:

    输入:date = "6th Jun 1933"
    输出:"1933-06-06"

    示例 3:

    输入:date = "26th May 1960"
    输出:"1960-05-26"

    提示:

    • 给定日期保证是合法的,所以不需要处理异常输入。

    主要思路:字符串分割
    Code:

    class Solution {
    public:
    void str_split(const std::string & src, const std::string & sep, std::vector<string> & vec_str)
    {
    std::string::size_type start = 0;
    int i=0;
    for(std::string::size_type end = src.find(sep, start); end != std::string::npos; end = src.find(sep, start))
    {
    if(end > start)
    {
    string str=src.substr(start, end - start);
    vec_str.push_back(str);
    }
    start = end + sep.length();
    }
    if(start < src.length())
    {
    string str=src.substr(start, src.length() - start);
    vec_str.push_back(str);
    }
    }
    string reformatDate(string date) {
    string day[]={"1st", "2nd", "3rd", "4th",
    "5th", "6th","7th",
    "8th", "9th","10th",
    "11th", "12th","13th",
    "14th", "15th","16th",
    "17th", "18th","19th",
    "20th", "21th","22th",
    "23th", "24th","25th",
    "26th", "27th","28th",
    "29th", "30th","31st"};
    string Month []={"Jan", "Feb", "Mar",
    "Apr", "May", "Jun",
    "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"};
    vector<string>vec;
    str_split(date," ",vec);
    string res="";
    res+=vec[2];
    res+="-";
    for(int i=0;i<sizeof(Month)/sizeof(string);i++)
    {
    if(vec[1]==Month[i])
    {
    char str[3]={0};
    sprintf(str,"%02d",i+1);
    res+=string(str);
    res+="-";
    }
    }
    if(vec[0].length()==3)
    {
    int day=atoi(vec[0].substr(0,1).c_str());
    char str[3]={0};
    sprintf(str,"%02d",day);
    res+=string(str);
    }
    else
    {
    int day=atoi(vec[0].substr(0,2).c_str());
    char str[3]={0};
    sprintf(str,"%02d",day);
    res+=string(str);
    }
    return res;
    }
    };
    posted @   萧海~  阅读(22)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · winform 绘制太阳,地球,月球 运作规律
    · AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
    · 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
    · 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
    · 上周热点回顾(3.3-3.9)
    历史上的今天:
    2021-05-14 字符串复制中的while条件
    2021-05-14 c++ scandir
    2021-05-14 c++string类默认函数实现
    2021-05-14 动态拼接字符串
    2021-05-14 百度API调用——语音识别
    点击右上角即可分享
    微信分享提示
    电磁波切换