题目描述
给定一个开门和关门时间,格式为“mon 11:22 am”,计算出在这段时间之内所有以5mins为单元的时间列表。
没找到Leetcode原题,应该是一道doordash改编题。
题目链接
https://www.1point3acres.com/bbs/thread-828828-1-1.html
题目思路
基本套路就是先处理时间,将“hh:mm”转化为分钟,起始时间:5-(总分钟%5) + 总分钟;终止时间:总分钟 - (5-(总分钟%5))。
然后将这个区间内所有5mins为单位的时间找出,列入最终结果即可。
public static List<String> getAllTimes(String[] times) {
HashMap<String, Integer> week = new HashMap<>();
String[] wstr = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};
for (int i=0; i<wstr.length; i++) {
week.put(wstr[i], i+1);
}
// process times
String[] time1 = times[0].split(" ");
int w1 = week.get(time1[0]);
String[] t1 = time1[1].split(":");
int h1 = Integer.parseInt(t1[0]);
int m1 = Integer.parseInt(t1[1]);
boolean isMorn1 = time1[2].equals("am");
if (isMorn1 && h1==12) h1 = 0;
if (!isMorn1 && h1!=12) h1+=12;
String[] time2 = times[1].split(" ");
int w2 = week.get(time2[0]);
String[] t2 = time2[1].split(":");
int h2 = Integer.parseInt(t2[0]);
int m2 = Integer.parseInt(t2[1]);
boolean isMorn2 = time2[2].equals("am");
if (isMorn2 && h2==12) h2 = 0;
if (!isMorn2 && h2!=12) h2+=12;
// check start point and endpoint
int st = h1*60 + m1;
int ed = h2*60 + m2;
int r1 = 5 - (st%5) + st;
int r2 = ed - (5 - (ed%5));
//
List<String> res = new ArrayList<>();
add(res, w1, st, ed);
return res;
}
private static void add(List<String> res, int week, Integer st, Integer ed) {
if (st != null && ed == null) {
for (int i = st; i<24*60; i++) {
if (i%5!=0) continue;
String th = i/60<10? "0"+i/60: ""+i/60;
String tm = i%60<10? "0"+i%60: ""+i%60;
String tmp = "" + week + th + tm;
res.add(tmp);
}
} else if (st == null && ed != null) {
for (int i = 0; i<=ed; i++) {
if (i%5!=0) continue;
String th = i/60<10? "0"+i/60: ""+i/60;
String tm = i%60<10? "0"+i%60: ""+i%60;
String tmp = "" + week + th + tm;
res.add(tmp);
}
} else if (st == null && ed == null) {
for (int i=0; i<24*60; i++) {
if (i%5!=0) continue;
String th = i/60<10? "0"+i/60: ""+i/60;
String tm = i%60<10? "0"+i%60: ""+i%60;
String tmp = "" + week + th + tm;
res.add(tmp);
}
} else if (st != null && ed != null) {
for (int i=st; i<ed; i++) {
if (i%5!=0) continue;
String th = i/60<10? "0"+i/60: ""+i/60;
String tm = i%60<10? "0"+i%60: ""+i%60;
String tmp = "" + week + th + tm;
res.add(tmp);
}
}
}