public class Solution { public string LargestTimeFromDigits(int[] A) { var list = Perm(A, 0); var maxHour = -1; var maxMinute = -1; foreach (var nums in list) { var hour = nums[0].ToString() + nums[1].ToString(); var minute = nums[2].ToString() + nums[3].ToString(); var strtime = hour + ":" + minute; if (ValidTime(strtime)) { var Inthour = Convert.ToInt32(hour); var IntMinute = Convert.ToInt32(minute); if ((Inthour > maxHour) || (Inthour == maxHour && IntMinute >= maxMinute)) { maxHour = Inthour; maxMinute = IntMinute; } } } if (maxHour >= 0) { var tempHour = maxHour.ToString(); var tempMinute = maxMinute.ToString(); if (tempHour.Length == 1) { tempHour = "0" + tempHour; } if (tempMinute.Length == 1) { tempMinute = "0" + tempMinute; } return tempHour + ":" + tempMinute; } else { return ""; } } private void Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; } private IEnumerable<int[]> Perm(int[] arr, int pos) { if (pos == arr.Length) { yield return arr; } for (int i = pos; i < arr.Length; ++i) { Swap(ref arr[i], ref arr[pos]); foreach (var j in Perm(arr, pos + 1)) yield return j; Swap(ref arr[i], ref arr[pos]); } } /// <summary> /// 判断时间格式是否合法 /// </summary> /// <param name="time"></param> /// <returns></returns> private bool ValidTime(string time) { var part = time.Split(':'); var hour = Convert.ToInt32(part[0]); var minute = Convert.ToInt32(part[1]); if (hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59) { return true; } return false; } }
这题又长又卵,没意思。