3333. 找到初始输入字符串 II

3333. 找到初始输入字符串 II


题目链接:3333. 找到初始输入字符串 II

代码如下:

//参考链接:https://leetcode.cn/problems/find-the-original-typed-string-ii/solutions/3706277/zhao-dao-chu-shi-shu-ru-zi-fu-chuan-ii-b-ldyv
class Solution {
public:
	int possibleStringCount(string word, int k) {
		int n = word.size(), cnt = 1;
		vector<int> freq;
		for (int i = 1;i < n;i++) {
			if (word[i] == word[i - 1]) {
				cnt++;
			}
			else {
				freq.push_back(cnt);
				cnt = 1; // 重置计数器
			}
		}
		freq.push_back(cnt); // 添加最后一组计数

		int res = 1;
		for (int o : freq) {
			res = static_cast<long long>(res) * o % mod; // 计算每组的可能性
		}

		if (freq.size() >= k) {
			return res;
		}

		vector<int> f(k), g(k, 1);
		f[0] = 1; // 初始化 f 数组
		for (int i = 0;i < freq.size();i++) {
			vector<int> f_new(k);
			for (int j = 1;j < k;j++) {
				f_new[j] = g[j - 1];
				if (j - freq[i] - 1 >= 0) {
					f_new[j] = (f_new[j] - g[j - freq[i] - 1] + mod) % mod;
				}
			}
			vector<int> g_new(k);
			g_new[0] = f_new[0];
			for (int j = 1;j < k;j++) {
				g_new[j] = (g_new[j - 1] + f_new[j]) % mod;
			}
			f = move(f_new);
			g = move(g_new); // 更新 f 和 g 数组
		}
		return (res - g[k - 1] + mod) % mod;
	}

private:
	static const int mod = 1'000'000'007;
};

你可能感兴趣的:(leetcode,c++)