Сортировать массив строк дат в порядке возрастания
Опубликовано: 15 Января, 2022
Учитывая массив строк date [] , задача состоит в том, чтобы отсортировать эти даты в порядке возрастания.
Примечание. Каждая дата имеет вид дд ммм гггг, где:
- Домен dd - [0-31] .
- Домен mmm : [Янв, Фев, Мар, Апрель, Май, Июнь, Июль, Август, Сен, Октябрь, Ноябрь, Дек] .
- И yyyy - это четырехзначное целое число.
Примеры:
Input: dates[] = {“01 Mar 2015”, “11 Apr 1996”, “22 Oct 2007”}
Output:
11 Apr 1996
22 Oct 2007
01 Mar 2015Input: dates[] = {“03 Jan 2018”, “02 Jan 2018”, “04 Jan 2017”}
Output:
04 Jan 2017
02 Jan 2018
03 Jan 2018
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход: извлеките дни , месяцы и годы как подстроки из строки, затем сравните две строки по годам , если годы для двух дат равны, сравните их месяцы . Если месяцы также равны дням, будет решено, какая дата появится в календаре раньше.
Below is the implementation of the above approach:
// C++ program to sort the dates in a string array #include <bits/stdc++.h> using namespace std; // Map to store the numeric value of each month depending on // its occurrence i.e. Jan = 1, Feb = 2 and so on. unordered_map<string, int > monthsMap; // Function which initializes the monthsMap void sort_months() { monthsMap[ "Jan" ] = 1; monthsMap[ "Feb" ] = 2; monthsMap[ "Mar" ] = 3; monthsMap[ "Apr" ] = 4; monthsMap[ "May" ] = 5; monthsMap[ "Jun" ] = 6; monthsMap[ "Jul" ] = 7; monthsMap[ "Aug" ] = 8; monthsMap[ "Sep" ] = 9; monthsMap[ "Oct" ] = 10; monthsMap[ "Nov" ] = 11; monthsMap[ "Dec" ] = 12; } // Comparator function to sort an array of dates bool comp(string a, string b) { // Comparing the years string str1 = a.substr(7, 5); string str2 = b.substr(7, 5); if (str1.compare(str2) != 0) { if (str1.compare(str2) < 0) return true ; return false ; } // Comparing the months string month_sub_a = a.substr(3, 3); string month_sub_b = b.substr(3, 3); // Taking numeric value of months from monthsMap int month_a = monthsMap[month_sub_a]; int month_b = monthsMap[month_sub_b]; if (month_a != month_b) { return month_a < month_b; } // Comparing the days string day_a = a.substr(0, 2); string day_b = b.substr(0, 2); if (day_a.compare(day_b) < 0) return true ; return false ; } // Utility function to print the contents // of the array void printDates(string dates[], int n) { for ( int i = 0; i < n; i++) { cout << dates[i] << endl; } } // Driver code int main() { string dates[] = { "24 Jul 2017" , "25 Jul 2017" , "11 Jun 1996" , "01 Jan 2019" , "12 Aug 2005" , "01 Jan 1997" }; int n = sizeof (dates) / sizeof (dates[0]); // Order the months sort_months(); // Sort the dates sort(dates, dates + n, comp); // Print the sorted dates printDates(dates, n); } |
Output:
11 Jun 1996 01 Jan 1997 12 Aug 2005 24 Jul 2017 25 Jul 2017 01 Jan 2019
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.