当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

Install win virtual machine on VMware
6 rules to sanitize your code
Quotefancy ,提供鼓舞人心语录的壁纸网站 - 倾城之链

Synchronization lock synchronized traces the source
![This article lets you quickly understand implicit type conversion [integral promotion]!](/img/16/4edc7ef23384b22d50ebd894b8911a.png)
This article lets you quickly understand implicit type conversion [integral promotion]!

xctf攻防世界 Web高手进阶区 ics-05

孙正义亏掉1500亿:当初投贵了

Js fifteen interview questions (with answers)

聊天尬死名场面,你遇到过吗?教你一键获取斗图表情包,晋升聊天达人

Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
随机推荐
Js fifteen interview questions (with answers)
十步以内,用小程序快速生成App!
【LaTex】 Font “FandolSong-Regular“ does not contain requested(fontspec)Script “CJK“.如何抑制此种警告?
关于ETL的两种架构(ETL架构和ELT架构)
mysql 找不到或无法加载已注册的 .Net Framework Data Provider。
你真的了解乐观锁和悲观锁吗?
用户代码未处理MetadataException
在“企业通讯录”的盲区,融云的边界与分寸
String hashing (2014 SERC J question)
级联下拉菜单的实现「建议收藏」
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
D. Binary String To Subsequences
18-GuliMall 压力测试与性能监控
Presto Event Listener开发
基于ABP的AppUser对象扩展
1215 – Cannot add foreign key constraint
重要的不是成为海贼王,而是像路飞一样去冒险
Redis
A. Common Prefixes
重装系统后新建文本文档打不开怎么办