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

SQLi-LABS Page-2 (Adv Injections)

Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!

【LaTex】 Font “FandolSong-Regular“ does not contain requested(fontspec)Script “CJK“.如何抑制此种警告?

国内手机厂商曾为它大打出手,如今它却最先垮台……

台风生成,广州公交站场积极开展台风防御安全隐患排查

Arcgis工具箱无法使用,显示“XML包含错误“的解决方法

C 在函数声明前加typedef

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

Converting angles to radians

2022 首期线下 Workshop!面向应用开发者们的数据应用体验日来了 | TiDB Workshop Day
随机推荐
面试官:Redis 大 key 要如何处理?
【EF】 更新条目时出错。有关详细信息,请参见内部异常。[通俗易懂]
17-GuliMall 搭建虚拟域名访问环境
第 1 章 一大波数正在靠近——排序
SecureCRT background color
typedef和#define的花里胡哨的用法
十步以内,用小程序快速生成App!
Basic operations of openGauss database (super detailed)
小程序+自定义插件的关键性
Flask入门学习教程
Leetcode.25 K个一组翻转链表(模拟/递归)
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
NodeJS使用JWT
R语言使用mean函数计算样本(观测)数据中指定变量的相对频数:计算时间序列数据中大于前一个观测值的观测值所占的比例总体的比例
Under the NVM node installation;The node environment variable configuration
Technology Sharing | How to use the JSON Schema mode of interface automation testing?
R语言将列表数据转化为向量数据(使用unlist函数将列表数据转化为向量数据)
从源码方面来分析Fragment管理中 Add() 方法
The kvm virtual machine cannot be started, NOT available, and the PV is larger than the partition
开发者必备:一文快速熟记【数据库系统】和【软件开发模型】常用知识点