Step-by-Step

[Java] Daily LeetCode Challenge 2466. Count Ways To Build Good Strings 본문

언어/JAVA

[Java] Daily LeetCode Challenge 2466. Count Ways To Build Good Strings

희주(KHJ) 2023. 5. 13. 12:57

https://leetcode.com/problems/count-ways-to-build-good-strings/

 

Count Ways To Build Good Strings - LeetCode

Can you solve this real interview question? Count Ways To Build Good Strings - Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following: * Append the char

leetcode.com

 

100 solved 달성! 백준, 프로그래머스도 좋지만 깃허브처럼 submission 잔디 보여주는게 너무 좋다 ㅎㅅㅎ 더 분발하자!

 

 

전형적인 DP 문제, 한 번 이어붙일때 1은 one(변수)만큼 써야하고 0은 zero(변수)만큼 써야함.

모듈러 연산이랑 low ~ high일때 dp 값 더해서 값 구해주면 됨!

 

[코드]

class Solution {
    public int mod = (int)1e9+7;
    public int countGoodStrings(int low, int high, int zero, int one) {
        int[] dp = new int[high+1]; dp[0]=1;
        int ans = 0;
        for(int i=1; i<=high; i++){
            if(i>=zero)
                dp[i]+=dp[i-zero]%mod;
            if(i>=one)
                dp[i]+=dp[i-one]%mod;
            dp[i] %= mod;
        }

        for(int i=low; i<=high; i++)
            ans = (ans+dp[i])%mod;

        return ans;
    }
}

 

Comments