当前位置:网站首页>leetcode:320.列举单词的全部缩写
leetcode:320.列举单词的全部缩写
2022-08-09 22:01:00 【OceanStar的学习笔记】
题目来源
题目描述
请你写出一个能够举单词全部缩写的函数。
注意:输出的顺序并不重要。
示例:
输入: "word"
输出:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d",
"wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
题目解析
仔细观察示例,发现word有4个字母时,会生成16个缩写,如果把0到15的二进制写出来,每一个可以对应一种情况,如下所示:
0000 word
0001 wor1
0010 wo1d
0011 wo2
0100 w1rd
0101 w1r1
0110 w2d
0111 w3
1000 1ord
1001 1or1
1010 1o1d
1011 1o2
1100 2rd
1101 2r1
1110 3d
1111 4
那么我们就可以观察出规律,凡是0的地方都是原来的字母,单独的1还是1,如果是若干个1连在一起的话,就要求出1的个数,用这个数字来替换对应的字母
class Solution {
void helper(string word, int pos, vector<string> &res) {
for (int i = pos; i < word.size(); ++i) {
// 前缀[0, i)
for (int j = 1; i + j <= word.size(); ++j) {
string t = word.substr(0, i);
// "" + 1 + ord
// "" + 2 + rd
// "" + 3 + d
// "" + 4
// w + 1 + od
// w + 2 + d
// w + 3
t += to_string(j) + word.substr(i + j);
res.push_back(t);
helper(t, i + 1 + to_string(j).size(), res);
}
}
}
public:
vector<string> generateAbbreviations(string word) {
vector<string> res{
word};
helper(word, 0, res);
return res;
}
};
实现二:
class Solution {
// 当前正在对word[idx]字符做决定, [0...idx)已经决定完了
// 在来到word[idx]位置之前,一共有多少个1连起来,
void helper(string word, int idx, int cnt, std::string path, vector<string> &ans) {
if(idx == word.size()){
if (cnt > 0) path += to_string(cnt);
ans.push_back(path);
}else{
helper(word, idx + 1, cnt + 1, path, ans); //当前位置用1替代
helper(word, idx + 1, 0, path + (cnt > 0 ? to_string(cnt) : "") + word[idx], ans); // 当前位置还是取原来的字符
}
}
public:
vector<string> generateAbbreviations(string word) {
vector<string> res;
helper(word, 0, 0, "", res);
return res;
}
};
边栏推荐
- How do task flow executors work?
- MLOps的演进历程
- Common commands and technical function modules of Metasploit
- Bean life cycle
- R语言ggplot2可视化:使用ggpubr包的ggerrorplot函数可视化误差线(可视化不同水平均值点以及se标准误差)、设置add参数为dotplot添加点阵图
- 重装系统后新建文本文档打不开怎么办
- leetcode 39. 组合总和(完全背包问题)
- Basic operations of openGauss database (super detailed)
- Metasploit常用命令、技术功能模块
- 电脑系统重装后怎么用打印机扫描出文件?
猜你喜欢
随机推荐
R语言将列表数据转化为向量数据(使用unlist函数将列表数据转化为向量数据)
D. Binary String To Subsequences
Converting angles to radians
为什么这么多人都想当产品经理?
【微服务~Nacos】Nacos服务提供者和服务消费者
力扣 1413. 逐步求和得到正数的最小值
mysql multi-table left link query
腾讯继续挥舞降本增效“大刀”,外包员工免费餐饮福利被砍了
Install win virtual machine on VMware
xctf攻防世界 Web高手进阶区 ics-05
Kubernetes Service对象
navicat 快捷键
你的 Link Button 能让用户选择新页面打开吗?
大型分布式存储方案MinIO介绍,看完你就懂了!
一本通2074:【21CSPJ普及组】分糖果(candy)
【测试】语句覆盖,判定覆盖,条件覆盖,路径覆盖
Space not freed after TRUNCATE table
js十五道面试题(含答案)
json case
Deceptive Dice









