11package com .devstromo .medium .p2266 ;
22
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
36public class Solution {
47 private static final int MOD = 1_000_000_007 ;
58
@@ -21,4 +24,63 @@ public int countTexts(String pressedKeys) {
2124
2225 return dp [n ];
2326 }
27+
28+ int mod = (int ) 1e9 + 7 ;
29+ int [] typeMap = new int []{-1 , -1 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 };
30+
31+ public int countTextsBest (String pressedKeys ) {
32+ // left * right
33+ List <int []> list = new ArrayList <>();
34+ int cnt = 0 , max = 0 ;
35+ char prev = '0' ;
36+ for (char c : pressedKeys .toCharArray ()) {
37+ if (prev != c ) {
38+ if (prev != '0' ) list .add (new int []{(prev - '0' ), cnt });
39+ max = Math .max (cnt , max );
40+ cnt = 0 ;
41+ }
42+ cnt ++;
43+ prev = c ;
44+ }
45+ if (cnt > 0 ) {
46+ list .add (new int []{(prev - '0' ), cnt });
47+ max = Math .max (max , cnt );
48+ }
49+
50+ long res = 1 ;
51+ Long [][] dp = new Long [2 ][max + 1 ];
52+ dp [0 ][0 ] = 1l ;
53+ dp [1 ][0 ] = 1l ;
54+ for (int i = 0 ; i < list .size (); i ++) {
55+ int [] cur = list .get (i );
56+ int num = cur [0 ], curCnt = cur [1 ];
57+ int type = typeMap [num ];
58+
59+ long combination = helper (type , curCnt , dp );
60+
61+ res = (res * combination ) % mod ;
62+ }
63+
64+ return (int ) res ;
65+ }
66+
67+ // type 0 = 3 char
68+ // type 1 = 4 char
69+ long helper (int type , int cnt , Long [][] dp ) {
70+ if (dp [type ][cnt ] != null ) return dp [type ][cnt ];
71+
72+ for (int i = 1 ; i <= cnt ; i ++) {
73+ if (dp [type ][i ] != null ) continue ;
74+
75+ if (i == 1 ) dp [type ][i ] = 1l ;
76+ if (i == 2 ) dp [type ][i ] = 2l ;
77+ if (i == 3 ) dp [type ][i ] = 4l ;
78+ // System.out.println(i + " dp[type][i-1]: "+ dp[type][i-1]);
79+ if (i >= 4 ) {
80+ if (type == 0 ) dp [type ][i ] = (dp [type ][i - 1 ] + dp [type ][i - 2 ] + dp [type ][i - 3 ]) % mod ;
81+ else dp [type ][i ] = (dp [type ][i - 1 ] + dp [type ][i - 2 ] + dp [type ][i - 3 ] + dp [type ][i - 4 ]) % mod ;
82+ }
83+ }
84+ return dp [type ][cnt ];
85+ }
2486}
0 commit comments