---
# System prepended metadata

title: 0681. Next Closest Time
tags: [Leetcode, FaceBook, Medium]

---

# 0681. Next Closest Time
###### tags: `Leetcode` `FaceBook` `Medium`
Link: https://leetcode.com/problems/next-closest-time/
## 思路
参考[这个网址](https://leetcode.com/problems/next-closest-time/discuss/107773/Java-AC-5ms-simple-solution-with-detailed-explaination)

![](https://i.imgur.com/FX9Dbly.png)

## Code
```java=
class Solution {
    public String nextClosestTime(String time) {
        char[] result = time.toCharArray();
        char[] digits = new char[]{result[0], result[1], result[3], result[4]};
        Arrays.sort(digits);
        
        result[4] = findNext(digits, '9', result[4]);
        if(result[4] > time.charAt(4)) return new String(result);
        
        result[3] = findNext(digits, '5', result[3]);
        if(result[3] > time.charAt(3)) return new String(result);
        
        result[1] = findNext(digits, result[0]=='2'?'3':'9', result[1]);
        if(result[1] > time.charAt(1)) return new String(result);
        
        result[0] = findNext(digits, '2', result[0]);
        return new String(result);
    }
    public char findNext(char[] digits, char upperLimit, char curr){
        int idx = 0;
        boolean find = false;
        while(idx < digits.length){
            if(curr == digits[idx]){
                find = true;
            }
            else{
                if(find) break;
            }
            idx++;
        }
        if(idx == digits.length || digits[idx] > upperLimit) return digits[0];
        else return digits[idx];
    }
}
```