最长合法括号子串 && 子序列

本文介绍了两种解决括号匹配问题的方法:动态规划和栈。通过示例代码详细讲解了如何找到最长的有效括号子字符串及子序列。

150. 括号画家
题意:
求长度最长的合法括号子串
思路:
经典的dp解法
code:

#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 1e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f
目前提供的引用内容未直接涉及求长度为 $n$、字符集 $P \subseteq \{1, 2, \cdots, n\}$ 且字符最多出现两次的字符串 $a$ 在新定义下的本质不同子串个数的具体方法。不过可以尝试分析并提出一种可能的思路。 首先,需要生成所有满足条件的字符串 $a$。由于字符集 $P \subseteq \{1, 2, \cdots, n\}$ 且每个字符最多出现两次,可通过回溯法生成所有可能的字符串。 然后,对于生成的每个字符串 $a$,枚举其所有子串。对于每个子串,计算其对应的可重集。为了判断两个子串是否本质不同,可将可重集进行排序,将排序后的可重集作为该子串的一种“特征表示”,通过哈希表来记录已经出现过的可重集,从而统计本质不同子串的个数。 以下是一个可能的 Python 代码示例: ```python from collections import Counter # 生成所有满足条件的字符串 def generate_strings(n): def backtrack(path, used_chars): if len(path) == n: yield ''.join(map(str, path)) return for char in range(1, n + 1): if used_chars[char] < 2: new_used_chars = used_chars.copy() new_used_chars[char] += 1 yield from backtrack(path + [char], new_used_chars) used_chars = [0] * (n + 1) return list(backtrack([], used_chars)) # 计算字符串在新定义下的本质不同子串个数 def count_distinct_substrings(s): distinct_sets = set() n = len(s) for l in range(n): for r in range(l, n): sub_str = s[l:r + 1] char_counter = Counter(sub_str) sorted_counter = tuple(sorted(char_counter.items())) distinct_sets.add(sorted_counter) return len(distinct_sets) # 主函数 n = 3 strings = generate_strings(n) for s in strings: result = count_distinct_substrings(s) print(f"字符串 {s} 的本质不同子串个数: {result}") ``` 此代码首先生成所有满足条件的字符串,然后对于每个字符串,计算其在新定义下的本质不同子串个数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值