
解題思路
給定格式日期,那么就需要把年月日分離開,由于到達某個月的天數只有兩種情況(與閏年有關),那么可以提前構建到達每個月天數的陣列,在討論閏年的時候再單獨討論處理,這樣都是常數空間的時空復雜度,代碼如下:
代碼
class Solution {
public:
int dayOfYear(string date) {
int days[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
return month <= 2 ? days[month - 1] + day : days[month - 1] + day + 1;
}
return days[month - 1] + day;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/387809.html
標籤:其他
