leetcode 6058. 统计打字方案数java

https://leetcode-cn.com/problems/count-number-of-texts/

class Solution {
    //int[] buttons={0,0,3,3,3,3,3,4,3,4};
    long res=1;
    int mod=1000000007;
    long[][] dp; //dp[0]是3字符可能性的,dp[1]是4字符可能性的。dp[][i]表面长度为i的重复字符串的信息种类数。
    int n;
    public int countTexts(String pressedKeys) {
        n=pressedKeys.length();
        dp=new long[2][100010];

        init();

        int i=0,j=i+1;
        while(i<n){
            j=i;
            while(j+1<n&&pressedKeys.charAt(i)==pressedKeys.charAt(j+1)){
                j++;
            }
            //[i,j]
            long tmp;
            if(pressedKeys.charAt(i)=='7'||pressedKeys.charAt(i)=='9'){
                tmp=dp[1][j-i+1];
            }
            else{
                tmp=dp[0][j-i+1];
            }
            res=(res*tmp)%mod;
            i=j+1;
        }
        return (int)res;
    }
    public void init(){
        dp[0][0]=1;dp[0][1]=1;dp[0][2]=2;dp[0][3]=4;
        dp[1][0]=1;dp[1][1]=1;dp[1][2]=2;dp[1][3]=4;
        for(int i=4;i<=n;i++){
            dp[0][i]=dp[0][i-1]+dp[0][i-2]+dp[0][i-3];
            dp[0][i]%=mod;
            dp[1][i]=dp[1][i-1]+dp[1][i-2]+dp[1][i-3]+dp[1][i-4];
            dp[1][i]%=mod;
        }
    }
}

你可能感兴趣的:(LeetCode,leetcode,java,动态规划)