【leetcode】1239. Maximum Length of a Concatenated String with Unique Characters
2024-09-05 10:09:53
题目如下:
Given an array of strings
arr
. Strings
is a concatenation of a sub-sequence ofarr
which have unique characters.Return the maximum possible length of
s
.Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i]
contains only lower case English letters.
解题思路:首先过滤掉arr中有重复字符的元素,接下来就可以采用BFS的方法进行计算了。怎么判断两个字符串是否有相同字符呢?我的方法是把字符串转成二进制的方式,a对应2^0,c对应2^2,z对应2^25。这样的话,每一个字符串都可以计算出一个特征值,判断两个字符串是否有相同字符,只有判断两个特征值与操作的结果是否为0即可。
代码如下:
class Solution(object):
def maxLength(self, arr):
"""
:type arr: List[str]
:rtype: int
"""
arr_val = []
for i in arr:
val = 0
if len(set(list(i))) != len(i):continue
for j in i:
val |= 2**(ord(j) - ord('a'))
arr_val.append(val)
#print arr_val
queue = []
if len(arr_val) == 0:return 0
for (inx,val) in enumerate(arr_val):
queue.append((inx,val))
res = 0
while len(queue) > 0:
inx,val = queue.pop(0)
end = True
for i in range(inx+1,len(arr_val)):
if val & arr_val[i] != 0:continue
queue.append((i,val | arr_val[i]))
end = False
if end :
res = max(res,bin(val).count(''))
return res
最新文章
- 编译器开发系列--Ocelot语言7.中间代码
- UML简单例子
- UISegmentedControl 的使用
- 图片上传功能<;转>;http://blog.csdn.net/u011159417/article/details/50126023
- geoip2 domain
- CentOS7安装memcached
- Autoprefixer处理CSS3属性前缀
- HDU 4512 吉哥系列故事——完美队形(LCIS)
- CentOS6.5 一键部署运行环境shell脚本
- HDU 1253 胜利大逃亡(三维BFS)
- oracle 分区和分区索引
- Struts2+JQuery发送Ajax请求
- POJ1719- Shooting Contest(二分图最大匹配)
- 详解Objective-C的meta-class 分类: ios相关 ios技术 2015-03-07 15:41 51人阅读 评论(0) 收藏
- Android 几种网络请求的区别与联系
- go标准库的学习-errors
- Jmeter中使用外部的java文件
- MYSQL语句:创建、授权、查询、修改、统计分析等 一 用户的创建、权限设置、删除等
- SVN无法Cleanup
- Codeforces Round #345 (Div. 2) B. Beautiful Paintings 暴力