forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_248.java
105 lines (93 loc) · 3.34 KB
/
_248.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
public class _248 {
public static class Solution1 {
/**Credit: https://discuss.leetcode.com/topic/31386/concise-java-solution
*
Construct char arrays from low.length() to high.length()
Add stro pairs from outside
When left > right, add eligible count
*/
private static final char[][] pairs = {{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
public int strobogrammaticInRange(String low, String high) {
int[] count = {0};
for (int len = low.length(); len <= high.length(); len++) {
char[] c = new char[len];
dfs(low, high, c, 0, len - 1, count);
}
return count[0];
}
public void dfs(String low, String high , char[] c, int left, int right, int[] count) {
if (left > right) {
String s = new String(c);
if ((s.length() == low.length() && s.compareTo(low) < 0)
|| (s.length() == high.length() && s.compareTo(high) > 0)) {
return;
}
count[0]++;
return;
}
for (char[] p : pairs) {
c[left] = p[0];
c[right] = p[1];
if (c.length != 1 && c[0] == '0') {
continue;
}
if (left == right && p[0] != p[1]) {
continue;
}
dfs(low, high, c, left + 1, right - 1, count);
}
}
}
public static class Solution2 {
Map<Character, Character> map = new HashMap<>();
{
map.put('1', '1');
map.put('8', '8');
map.put('6', '9');
map.put('9', '6');
map.put('0', '0');
}
String low = "";
String high = "";
public int strobogrammaticInRange(String low, String high) {
this.low = low;
this.high = high;
int result = 0;
for (int n = low.length(); n <= high.length(); n++) {
int[] count = new int[1];
strobogrammaticInRange(new char[n], count, 0, n - 1);
result += count[0];
}
return result;
}
private void strobogrammaticInRange(char[] arr, int[] count, int lo, int hi) {
if (lo > hi) {
String s = new String(arr);
if ((arr[0] != '0' || arr.length == 1) && compare(low, s) && compare(s, high)) {
count[0]++;
}
return;
}
for (Character c : map.keySet()) {
arr[lo] = c;
arr[hi] = map.get(c);
if ((lo == hi && c == map.get(c)) || lo < hi) {
strobogrammaticInRange(arr, count, lo + 1, hi - 1);
}
}
}
private boolean compare(String a, String b) {
if (a.length() != b.length()) {
return a.length() < b.length();
}
int i = 0;
while (i < a.length() && a.charAt(i) == b.charAt(i)) {
i++;
}
return i == a.length() ? true : a.charAt(i) <= b.charAt(i);
}
}
}