问题描述
小明正在整理一批历史文献。这些历史文献中出现了很多日期。小明知道这些日期都在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
时间限制:1.0s 内存限制:256.0MB
思路
(1)需要对小于10的数进行补零
(2)需要考虑到重复的情况,去重
(3)需要对日期进行排序 => 因此这里可以借助set,先排好序,再按格式输出
我提交的时候,发现了一个问题,如果是用hashset,一直fail过不去,找不到问题。然后我改成了treeset就可以通过,所以以后尽量还是用Treeset进行提交。
代码:
import java.util.*;
public class Main {
static int[] m = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static List<Integer> list = new ArrayList<>(); // list
static TreeSet<Integer> set = new TreeSet<>(); // set 会去重,并自动排好序
// 判断闰年
static int judge(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
return 0;
}
// 获取每个月的天数
static int getDays(int year, int month) {
if (month == 2) return 28 + judge(year);
return m[month];
}
static void func(int year, int month, int day) {
if (year <= 59)
year = year + 2000;
else
year = year + 1900;
if (month <= 12 && month >= 1 && getDays(year, month) >= day && day > 0) {
if (month < 10 && day < 10)
set.add(Integer.parseInt("" + year + "0" + month + "0" + day));
else if (month < 10)
set.add(Integer.parseInt("" + year + "0" + month + day));
else if (day < 10)
set.add(Integer.parseInt("" + year + month + "0" + day));
else
set.add(Integer.parseInt("" + year + month + day));
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str;
str = scanner.next();
int a, b, c;
String[] s = str.split("/");
a = Integer.parseInt(s[0]);
b = Integer.parseInt(s[1]);
c = Integer.parseInt(s[2]);
// AA/BB/CC CC/AA/BB CC/BB/AA
func(a, b, c);
func(c, a, b);
func(c, b, a);
list.addAll(set);
for (int i = 0; i < list.size(); i++) {
String result = "" + list.get(i);
System.out.println(result.substring(0, 4) + "-" + result.substring(4, 6) + "-" + result.substring(6, 8));
}
}
}