Given a date
string in the form Day Month Year
, where:
Day
is in the set{"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}
.Month
is in the set{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
.Year
is in the range[1900, 2100]
.
Convert the date string to the format YYYY-MM-DD
, where:
YYYY
denotes the 4 digit year.MM
denotes the 2 digit month.DD
denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Approach
Java
import java.util.HashMap;public class ReformatDate {public static void main(String[] args) {String date = "20th Oct 2052";System.out.println(reformatDate(date));}// function to reformat the given datestatic String reformatDate(String s) {int n = s.length();int i = 0;String str = "";while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') {str += s.charAt(i);i++;}while (s.charAt(i) != ' ')i++;i++;String str1 = "";int k = i;for (int j = k; j < k + 3; j++) {str1 += s.charAt(j);i++;}while (s.charAt(i) == ' ')i++;int cnt = 0;String str2 = "";while (i < n) {str2 += s.charAt(i);i++;cnt++;if (cnt == 4)break;}String res = "";for (int j = 0; j < str2.length(); j++)res += str2.charAt(j);res += '-';HashMap<String, String> mp = new HashMap<String, String>();mp.put("Jan", "01");mp.put("Feb", "02");mp.put("Mar", "03");mp.put("Apr", "04");mp.put("May", "05");mp.put("Jun", "06");mp.put("Jul", "07");mp.put("Aug", "08");mp.put("Sep", "09");mp.put("Oct", "10");mp.put("Nov", "11");mp.put("Dec", "12");res += mp.get(str1);res += '-';if (str.length() == 1) {res += "0";res += str.charAt(0);} else {res += str.charAt(0);res += str.charAt(1);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to reformat the given datestring reformatDate(string s){int n = s.size();int i = 0;string str = "";while (i < n && s[i] >= '0' && s[i] <= '9'){str += s[i];i++;}while (s[i] != ' ')i++;i++;string str1 = "";int k = i;for (int j = k; j < k + 3; j++){str1 += s[j];i++;}while (s[i] == ' ')i++;int cnt = 0;string str2 = "";while (i < n){str2 += s[i];i++;cnt++;if (cnt == 4)break;}string res = "";for (int i = 0; i < str2.size(); i++)res += str2[i];res += '-';map<string, string> mp;mp["Jan"] = "01";mp["Feb"] = "02";mp["Mar"] = "03";mp["Apr"] = "04";mp["May"] = "05";mp["Jun"] = "06";mp["Jul"] = "07";mp["Aug"] = "08";mp["Sep"] = "09";mp["Oct"] = "10";mp["Nov"] = "11";mp["Dec"] = "12";res += mp[str1];res += '-';if (str.size() == 1){res += "0";res += str[0];}else{res += str[0];res += str[1];}return res;}int main(){string date = "20th Oct 2052";cout << reformatDate(date);return 0;}
No comments:
Post a Comment