Java going through all permutations


  • 0
    W

    class Solution {
    public String nextClosestTime(String time) {
    int[] perms = new int[4];
    perms[0]=time.charAt(0)-'0'; perms[1]=time.charAt(1)-'0'; perms[2]=time.charAt(3)-'0'; perms[3]=time.charAt(4)-'0';
    List<Integer> res = new ArrayList<>();
    for (int i=0;i<4;i++){
    for (int j=0;j<4;j++){
    for (int k=0;k<4;k++){
    for (int l=0;l<4;l++){
    StringBuilder sb = new StringBuilder();
    sb.append(perms[i]);
    sb.append(perms[j]);
    sb.append(perms[k]);
    sb.append(perms[l]);
    if (isValidTime(sb.toString()) && !res.contains(Integer.parseInt(sb.toString()))) res.add(Integer.parseInt(sb.toString()));
    }
    }
    }
    }
    Collections.sort(res);
    int acttime = Integer.parseInt(time.substring(0,2) + time.substring(3));
    int fin = 0;
    if (res.indexOf(acttime) == res.size()-1) fin = res.get(0);
    else fin = res.get(res.indexOf(acttime)+1);
    String realfin = zeroPad(fin);
    return realfin.substring(0,2) + ":" + realfin.substring(2);
    }
    private String zeroPad (int fin) {
    if (fin<10) return "000" + fin;
    if (fin<60) return "00" + fin;
    if (fin<960) return "0" + fin;
    return Integer.toString(fin);
    }
    private boolean isValidTime(String time){
    if (time.charAt(0)-'0'>2) return false;
    if (time.charAt(0)-'0'==2 && time.charAt(1)-'0'>3) return false;
    if (time.charAt(2)-'0'>5) return false;
    return true;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.