題目如下 :
7,標題:日期問題
小明正在整理一批歷史文獻。這些歷史文獻中出現了很多日期。小明知道這些日期都在1960年1月1日至2059年12月31日。令小明頭疼的是,這些日期採用的格式非常不統一,有采用年/月/日的,有采用月/日/年的,還有采用日/月/年的。更加麻煩的是,年份也都省略了前兩位,使得文獻上的一個日期,存在很多可能的日期與其對應。
比如02/03/04,可能是2002年03月04日、2004年02月03日或2004年03月02日。
給出一個文獻上的日期,你能幫助小明判斷有哪些可能的日期對其對應嗎?
輸入
----
一個日期,格式是"AA/BB/CC"。 (0 <= A, B, C <= 9)
輸出
----
輸出若干個不相同的日期,每個日期一行,格式是"yyyy-MM-dd"。多個日期按從早到晚排列。
樣例輸入
----
02/03/04
樣例輸出
----
2002-03-04
2004-02-03
2004-03-02
資源約定:
峯值內存消耗(含虛擬機) < 256M
CPU消耗 < 1000ms
算法設計:本題總的來說設計比較簡單,問題的關鍵在與如何將時間從早到晚排序,由於時間的排序其實和字典序是一樣的,所以可以將三種情況得到的時間變爲字符串添加到一個list<String>中,然後調用Collections.sort(list),list中的字符串就會自動按照字典序排序好,說實話,本題看起來十分簡單,但是我着實浪費了不少時間,原因是一來就上手寫,沒有想好算法,以爲很簡單就隨手寫,結果浪費了很多時間,所以無論什麼題,現在腦海中構思好主體的算法再下手寫。
代碼如下:
import java.util.*;
public class Seven {
static List<String> results = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String now = sc.next();
results = new LinkedList<String>();
String[] temp = now.split("/");
int[] dates = {Integer.valueOf(temp[0]),Integer.valueOf(temp[1]),Integer.valueOf(temp[2])};
//按照年月日
get(dates[0],dates[1],dates[2]);
//按照月日年
get(dates[2],dates[0],dates[1]);
//按照日月年
get(dates[2],dates[1],dates[0]);
Collections.sort(results);
for(String i:results){
System.out.println(i);
}
}
public static void get(int year,int month,int day){//將對應的時間按照要求轉爲字符串,加到results列表中
if(isCorrect(year,month,day)){
String atemp,btemp,ctemp;
if(year>=60){
atemp = "19"+year;
}else if(year<10){
atemp = "200"+year;
}else{
atemp = "20"+year;
}
if(month<10){
btemp = "0"+month;
}else{
btemp = ""+month;
}
if(day<10){
ctemp = "0"+day;
}else{
ctemp = ""+day;
}
String temp = atemp+"-"+btemp+"-"+ctemp;
results.add(temp);
}
}
public static boolean isCorrect(int year,int month,int day){ //判斷時間是否正確的時間
boolean result = true;
if(month>13){
return false;
}
if(month==2){
if((year%4==0&&year%100!=0)||year%400==0){
if(day>28){
return false;
}
}else if(day>29){
return false;
}
}
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
if(day>31){
return false;
}
}
if(month==4||month==6||month==9||month==11){
if(day>30){
return false;
}
}
return true;
}
}
結果如下 :