lifeiteng

681. Next Closest Time

Sep 10th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. class Solution {
  2.     public String nextClosestTime(String time) {
  3.         List<Integer> list = new ArrayList<>();
  4.         int[] f = new int[10];
  5.         for(char ch : time.toCharArray())
  6.             if(ch != ':') f[ch - '0']++;  // collect all characters
  7.         for(int i = 0; i < 10; i++) if(f[i] > 0) list.add(i);
  8.         dfs(list, new char[4], 0);
  9.         // now loop through genTimes
  10.         // System.out.println(genTimes);
  11.         int inf = Integer.MAX_VALUE, diff = inf;
  12.         String res = "";
  13.         for(String times : genTimes)
  14.         {
  15.             if(!isvalid(times)) continue;
  16.             int timeDifference = timeDiff(time, times);
  17.             if(timeDifference < diff)
  18.             {
  19.                 diff = timeDifference;
  20.                 res = times;
  21.             }
  22.         }
  23.         return res.substring(0, 2) + ":" + res.substring(2);
  24.     }
  25.    
  26.     int timeDiff(String str1, String str2)
  27.     {
  28.         int h1 = Integer.valueOf(str1.substring(0, 2)), m1 = Integer.valueOf(str1.substring(3)),
  29.             h2 = Integer.valueOf(str2.substring(0, 2)), m2 = Integer.valueOf(str2.substring(2));
  30.         int time1 = h1 * 60 + m1, time2 = h2 * 60 + m2;
  31.         if(time1 < time2) return time2 - time1;
  32.         else return time2 + 24 * 60 - time1;
  33.     }
  34.    
  35.     boolean isvalid(String str)
  36.     {
  37.         int hour = Integer.valueOf(str.substring(0, 2)), min = Integer.valueOf(str.substring(2));
  38.         if(hour > 23 || min > 59) return false;
  39.         return true;
  40.     }
  41.    
  42.     List<String> genTimes = new ArrayList<>();
  43.    
  44.     void dfs(List<Integer> list, char[] chs, int pos)
  45.     {
  46.         if(pos == 4)
  47.         {
  48.             String str = String.valueOf(chs);
  49.             if(isvalid(str)) genTimes.add(str);
  50.             return;
  51.         }
  52.         for(int k : list)
  53.         {
  54.             chs[pos] = (char)('0' + k);
  55.             dfs(list, chs, pos + 1);
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment