假设有一个字。我们必须定义一个函数,该函数可以生成单词的广义缩写。
因此,如果输入就像“ word”,那么输出将是[“ word”,“ 1ord”,“ w1rd”,“ wo1d”,“ wor1”,“ 2rd”,“ w2d”,“ wo2”,“ 1o1d”,“ 1or1”,“ w1r1”,“ 1o2”,“ 2r1”,“ 3d”,“ w3”,“ 4”]]
为了解决这个问题,我们将遵循以下步骤-
定义数组ret
定义一个函数solve(),它将使用s,idx,
如果idx> = s的大小,则-
在ret的末尾插入s
返回
y:= s的子串从索引0到idx-1
i:= y的大小
num:=空字符串
而(i> = 0且y [i] <= ASCII的'9'和y [i]> = ASCII的'0'),则执行-
num:= y [i] + num
(将i减1)
如果i不等于y的大小,则-
解决(ret,idx + 1)
ret:= s的子串从索引(0到idx-(y的大小-1-i)-1)并置(数字+ 1)作为字符串将s的子串从索引(0到idx)并置
s1:= num + 1作为字符串
s2:= num作为字符串
如果s1的大小与s2的大小相同,则-
除此以外
除此以外
上一个:= s [idx]
s [idx]:='1'
解决(S,IDX + 1)
s [idx]:=上一个
解决(S,IDX + 1)
从主要方法中执行以下操作-
解决(word,0)
返回ret
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<string> ret;
void solve(string s, int idx){
if (idx >= s.size()) {
ret.push_back(s);
return;
}
string y = s.substr(0, idx);
int i = y.size() - 1;
string num = "";
while (i >= 0 && y[i] <= '9' && y[i] >= '0') {
num = y[i] + num;
i--;
}
if (i != y.size() - 1) {
string ret = s.substr(0, idx - (y.size() - 1 - i)) + to_string(stoi(num) + 1) + s.substr(idx + 1);
string s1 = to_string(stoi(num) + 1);
string s2 = to_string(stoi(num));
if (s1.size() == s2.size())
solve(ret, idx);
else
solve(ret, idx + 1);
}
else {
char prev = s[idx];
s[idx] = '1';
solve(s, idx + 1);
s[idx] = prev;
}
solve(s, idx + 1);
}
vector<string< generateAbbreviations(string word){
solve(word, 0);
return ret;
}
};
main(){
Solution ob;
print_vector(ob.generateAbbreviations("hello"));
}hello
输出结果
[5, 4o, 3l1, 3lo, 2l2, 2l1o, 2ll1, 2llo, 1e3, 1e2o, 1e1l1, 1e1lo, 1el2, 1el1o, 1ell1, 1ello, h4, h3o, h2l1, h2lo, h1l2, h1l1o, h1ll1, h1llo, he3, he2o, he1l1, he1lo, hel2, hel1o, hell1, hello, ]