lc 0227
✅ 1189. “气球” 的最大数量
描述
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
思路:
bucket 数组,(或者用map/py 字典实现更好)
统计 ballon 这个字典里的最小数
cpp
todo watch
int maxNumberOfBalloons(char * text){
int* hashSet=(int*)malloc(sizeof(int)*128);
memset(hashSet,0,sizeof(int)*128);
int textLength = 0;
while(text[textLength]){
hashSet[text[textLength]]++;
textLength++;
}
int wordQty = textLength;
wordQty = (wordQty>hashSet['a'])?hashSet['a']:wordQty;
wordQty = (wordQty>hashSet['b'])?hashSet['b']:wordQty;
wordQty = (wordQty>hashSet['n'])?hashSet['n']:wordQty;
wordQty = (wordQty>(hashSet['o']>>1))?(hashSet['o']>>1):wordQty;
wordQty = (wordQty>(hashSet['l']>>1))?(hashSet['l']>>1):wordQty;
free(hashSet);
return wordQty;
}
py
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
mydict = {}
tgt = ['b','a','l','o','n']
for i in tgt:
mydict[i] = 0
for c in text:
if c in tgt:
mydict[c] = mydict[c] + 1 # # 这里是否需要初始化mydict的key value(=0)呢?
counter = mydict['a']
for k in mydict:
tmp1 = mydict[k]
if k == 'l' or k == 'o':
tmp = tmp1 // 2
if tmp < counter:
counter = tmp
else:
if tmp1 < counter:
counter = tmp1
return counter
'''执行用时 :
44 ms
, 在所有 Python3 提交中击败了
37.20%
的用户
内存消耗 :
13.5 MB
, 在所有 Python3 提交中击败了
35.66%
的用户'''
improved py
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
d = collections.Counter(text)
return min(d['b'], d['a'], d['l'] // 2, d['o'] // 2, d['n'])
✅ 784. 字母大小写全排列
https://leetcode-cn.com/problems/letter-case-permutation
描述
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
输入: S = "3z4"
输出: ["3z4", "3Z4"]
输入: S = "12345"
输出: ["12345"]
S 的长度不超过12。
S 仅由数字和字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-case-permutation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
思路:我们统计字母的数量 i,然后2的次方 之 : i^2,这是数量
为了构造i^2 个:howto todo
c: backTrace
!! powerful: backTrace; rev me; todo
//C语言实现,递归回溯 todo
#define MAX_SIZE 10240//tt do we really need so big space for g_re??
#define STR_SIZE 15
struct StrRecord {
char str[STR_SIZE];
int pos;
};
struct StrRecord g_str;
int g_num = 0;
char **g_re;//tt why double ptr here?: a ptr point other bunch of ptrs;
void backTrace(char *S, int len, int start)
{
//tt when the recursive goto the end (of the S)
//tt we can add the recursive result to the g_re.
if (g_str.pos == len) {
g_re[g_num++] = strdup(g_str.str);
}
//tt otherwise: we start from `start` to traverse
//tt all the left char in S(using S[i]);
//tt to set each alpha char to lower / upper
//tt each alpha has two possible output: lower / upper
for (int i = start; i < len; i++) {
if (isalpha(S[i])) {
int tmpLower = tolower(S[i]);
g_str.str[g_str.pos++] = tmpLower;
//tt backTrace always go to next
backTrace(S, len, i + 1);
//tt here we see: `g_str.pos--`
//tt which jst represent: BACKTrace
g_str.str[g_str.pos--];
int tmpUpper = toupper(S[i]);
g_str.str[g_str.pos++] = tmpUpper;
} else {
//tt when it's not alpha(aka num)
//tt all we need to do is give num to g_str.str
g_str.str[g_str.pos++] = S[i];
}
//tt watch this: two lines: are also the keys of backTrace!!
backTrace(S, len, i + 1);
g_str.str[g_str.pos--];
}
}
char **letterCasePermutation(char *S, int *returnSize)
{
g_re = malloc(sizeof(char *) * MAX_SIZE);
g_num = 0;
memset(&g_str, 0, sizeof(g_str));
int len = strlen(S);
backTrace(S, len, 0);
*returnSize = g_num;
return g_re;
}
py todo watch me; three me
本题跟78 很像
DFS 回溯 看到题目要求组合或者集合,马上想到可以用回溯法:回溯法本来是说对于每个元素都先考虑放它的情况,再考虑不放它的情况;放在这道题的背景里就是,对于每个字母,先考虑放它,再考虑放它的另一种大小写形式。
用dfs实现回溯,start代表目前从扫描到第几位,
如果是digit,就直接加进去,然后下一层递归
如果是alpha,就先加进去,然后下一层递归;再加对立大小写形式, 然后下一层递归。
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
ret = list()
l = len(S)
if l == 0:
return ['']# is the same as [""]? seems yes
def dfs(start, tmp):
if (start >= l or len(tmp) >= l):
# we already find one ans, so add it to ret
ret.append(tmp)
return
if S[start].isdigit():
dfs(start + 1, tmp + S[start])
elif S[start].islower():
dfs(start + 1, tmp + S[start])
dfs(start + 1, tmp + S[start].upper())
elif S[start].isupper():
dfs(start + 1, tmp + S[start])
dfs(start + 1, tmp + S[start].lower())
dfs(0, "")
return ret
'''
执行用时 :
116 ms
, 在所有 Python3 提交中击败了
17.12%
的用户
内存消耗 :
14.8 MB
, 在所有 Python3 提交中击败了
17.43%
的用户
'''
todo watch ⬇️
BFS 除了用DFS回溯实现,我们也可以用BFS来解题
线性扫描S,
对于扫描到的每个元素, 都把它的大小写形式分别加到,目前的res里的所有结果里,这样可以得到temp,
然后用temp覆盖res。
比如对于S = "a1b2",
扫描到a时, res = [a, A]
扫描到b时, res = [a1, A1], temp = [a1b, a1B, A1b, A1B]
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
import copy
res = [""]
for i, x in enumerate(S):
# if len(res) == 0:
# res.append(x)
if x.isdigit():#数字就每个答案都加进去
for index, item in enumerate(res):
res[index] += (x)
elif x.isupper():#字母就每个答案先放自己再放对立面
temp = list()
for index, item in enumerate(res):
# print item
temp.append(item + (x))
temp.append(item + (x.lower()))
res = copy.deepcopy(temp[:])
elif x.islower():
temp = list()
for index, item in enumerate(res):
temp.append(item + (x))
temp.append(item + (x.upper()))
res = copy.deepcopy(temp[:])
# print temp
return res
BitMap
Bitmap法,字符串S的长度为l, 则总共会有 2** l种结果,换成二进制就是0 ~ 2 **l - 1个数,
对于每个数,如果某个位上是0, 就放小写;是1, 就放大写。
class Solution(object):
def letterCasePermutation(self, S):
l = len(S)
n = 2 ** l
res = list()
if l == 0:
res.append("")
for i in range(0, n): #得到0 ~ 2 ** l 的每个数
temp = ""
for j in range(0, l):
if ((2 ** j) &i) == 0:#当前位是0, 放小写
temp += S[j].lower()
else: #放大写
temp += S[j].upper()
if temp not in res:
res.append(temp)
return res
lc 0227的更多相关文章
- 四种比较简单的图像显著性区域特征提取方法原理及实现-----> AC/HC/LC/FT。
laviewpbt 2014.8.4 编辑 Email:laviewpbt@sina.com QQ:33184777 最近闲来蛋痛,看了一些显著性检测的文章,只是简单的看看,并没有深入的研究,以 ...
- “LC.exe”错误
错误“LC.exe”已退出,代码为 -1. 可能的原因是: 这个第三方组件是个商业组件,他在组件的主使用类定义了 LicenseProvider(typeof(LicFileLicenseProvid ...
- 解决VS下“LC.exe已退出,代码为-1”问题
今天使用VS2015开发一个Winform程序,手一抖拖错了一个第三方控件,然后将其去掉并删除相关的引用,结果导致了LC.exe错误:"Lc.exe已退出,代码为-1 ". 经过上 ...
- 解析.NET 许可证编译器 (Lc.exe) 的原理与源代码剖析
许可证编译器 (Lc.exe) 的作用是读取包含授权信息的文本文件,并产生一个可作为资源嵌入到公用语言运行库可执行文件中的 .licenses 文件. 在使用第三方类库时,经常会看到它自带的演示程序中 ...
- Lc.exe已退出,代码为-1
编译项目,出现提示"Lc.exe已退出,代码为-1" . 解决办法: 意思就是把licenses.licx这个文件里的内容删除,但是文件还在(此时是个空文件),发生这个问题的原 ...
- "LC.exe" exited with code -1 错误
当打开一个VS程序时出现"LC.exe" exited with code -1错误,解决方法是: 删除licenses.licx文件即可
- LC.exe exited with code -1
昨天从win8.1升级到win10之后, 一切还算顺利, 就是升级时间比较长. 但是快下班的时候 遇到一个问题, 是之前在win8.1上没遇到的, 首先代码win8.1 vs2013 上跑的时候一切正 ...
- vs2012编译出错“LC.exe”已退出解决方法
“LC.exe”已退出,代码为 -1. 解决方法: 将项目Properties下的licenses.licx文件删除,重新编译即可.
- TT付款方式、前TT和后TT、LC信用证+TT付款方式
TT付款方式是以外汇现金方式结算,由您的客户将款项汇至贵公司指定的外汇银行账号内,可以要求货到后一定期限内汇款. .T/T属于商业信用,也就是说付款的最终决定权在于客户.T/T分预付,即期和远期.现在 ...
随机推荐
- ansible笔记(13):变量(二)
1.谈一谈[Gathering Facts]:使用setup模块查看 当我们运行一个playbook时,默认都会运行一个名为“[Gathering Facts]”的任务,前文中已经大致的介绍过这个默认 ...
- 【Python】输入身份证号,输出出生日期
name = input("请输入你的名字:") id = input("请输入你的身份证号码:") year = id[6:10] month = id[10 ...
- IIS支持json、geojson文件
最近在搞asp.net + openlayers. 其中openlayer有个数据源支持 .geojson 数据,但是怎么测试都不能成功.同样的数据拿到php下就能成功显示. 搓. 在网上漫无目的的搜 ...
- 如何查看mac多少位的操作系统?
1.点击工具栏左上角点击 (苹果Logo)标志,关于本机 --> 更多信息 --> 系统报告 -->(左侧栏中)软件 (有的电脑是没有的例如第一张图) 2. 输入命令 una ...
- AcWing 792. 高精度减法
https://www.acwing.com/problem/content/794/ #include<bits/stdc++.h> using namespace std; //判断是 ...
- AcWing 789. 数的范围 二分+模板
https://www.acwing.com/problem/content/791/ #include<bits/stdc++.h> using namespace std; ; int ...
- requests.packages.urllib3.exceptions.ProxySchemeUnknown: Not supported proxy scheme
python3 -m pip install -U requests[socks]
- Android开发实战——记账本(2)
开发日志(2)——Bean目录以及数据库 首先编写一些自己生成的数据进行测试,看一下能否显示在模拟器上.那前提就是先写出bean目录,这和之前学的Javaweb步骤差不多.bean目录有三个变量事件. ...
- 【音乐欣赏】《Abnormalize》 - 凛として時雨
曲名:Abnormalize 作者:凛として時雨 [00:00.96]誰にも見せられないもの [00:06.44]頭の中溢れて [00:11.96]間違いさえも無い世界へ [00:17.16]迷い込ん ...
- MinGW编译dll并引用
记得某位神仙曾经说过:一个项目不使用dll简直是一场灾难.(滑稽) 这篇文章以A+B/A-B为范例,来介绍如何在MinGW下编译dll并引用. 首先你要安装MinGW,并配置好环境变量(不配置环境变量 ...