@@ -8,7 +8,7 @@ public static class Solution1 {
8
8
/**
9
9
* My very original, but non-DP solution.
10
10
*/
11
- public int rotatedDigits (int N ) {
11
+ public int rotatedDigits (int n ) {
12
12
int count = 0 ;
13
13
Map <Character , String > map = new HashMap <>();
14
14
map .put ('0' , "0" );
@@ -18,7 +18,7 @@ public int rotatedDigits(int N) {
18
18
map .put ('5' , "2" );
19
19
map .put ('6' , "9" );
20
20
map .put ('9' , "6" );
21
- for (int i = 1 ; i <= N ; i ++) {
21
+ for (int i = 1 ; i <= n ; i ++) {
22
22
if (isRotatedNumber (i , map )) {
23
23
count ++;
24
24
}
@@ -39,4 +39,46 @@ private boolean isRotatedNumber(int num, Map<Character, String> map) {
39
39
return !originalNum .equals (sb .toString ());
40
40
}
41
41
}
42
+
43
+ public static class Solution2 {
44
+ /**
45
+ * credit: https://leetcode.com/problems/rotated-digits/discuss/117975/Java-dp-solution-9ms
46
+ * dp[i] = 0 means invalid;
47
+ * dp[i] = 1 means valid but the same;
48
+ * dp[i] = 2 means valid and different.
49
+ */
50
+ public int rotatedDigits (int n ) {
51
+ int [] dp = new int [n + 1 ];
52
+ int count = 0 ;
53
+ for (int num = 0 ; num <= n ; num ++) {
54
+ if (num < 10 ) {
55
+ if (num == 0 || num == 1 || num == 8 ) {
56
+ dp [num ] = 1 ;
57
+ } else if (num == 2 || num == 5 || num == 6 || num == 9 ) {
58
+ count ++;
59
+ dp [num ] = 2 ;
60
+ }
61
+ } else {
62
+ /**Here's the key/beauty of this DP solution:
63
+ * we could keep checking each number by reusing the previous number we worked on,
64
+ * basically, always break a bigger number into two parts: a number that's its right most digit and everything else, e.g.
65
+ * num = 12 -> 1 and 2, so we check dp[1] and dp[2] to know if 12 could be rotated to a valid number,
66
+ * num = 123 -> 12 and 3, so we check dp[12] and dp[3] to know if 123 could be rotated to a valid number.
67
+ * and so on.
68
+ * */
69
+ int a = dp [num / 10 ];
70
+ int b = dp [num % 10 ];
71
+ if (a == 1 && b == 1 ) {
72
+ //we first check if both are valid and the same, if that's the case, then we mark it as 1
73
+ dp [num ] = 1 ;
74
+ } else if (a >= 1 && b >= 1 ) {
75
+ //then only in this case, either a or b is greater than 1, it's a valid and different number
76
+ dp [num ] = 2 ;
77
+ count ++;
78
+ }
79
+ }
80
+ }
81
+ return count ;
82
+ }
83
+ }
42
84
}
0 commit comments