1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| private static final char[][] PAIRS = new char[][] { {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; public int strobogrammaticInRange(String low, String high) { if (low == null || high == null || low.length() > high.length() || (low.length() == high.length() && low.compareTo(high) > 0)) { return 0; } int count = 0; for (int len = low.length(); len <= high.length(); len++) { count += dfs(low, high, new char[len], 0, len - 1); } return count; } private int dfs(String low, String high, char[] ch, int left, int right) { if (left > right) { String s = new String(ch); if ((ch.length == low.length() && s.compareTo(low) < 0) || (ch.length == high.length() && s.compareTo(high) > 0)) { return 0; } else { return 1; } } int count = 0; for (char[] p : PAIRS) { ch[left] = p[0]; ch[right] = p[1]; if (ch.length != 1 && ch[0] == '0') { continue; } if (left == right && (p[0] == '6' || p[0] == '9')) { continue; } count += dfs(low, high, ch, left + 1, right - 1); } return count; }
|