C++ 中的广义缩写
假设有一个单词。我们需要定义一个函数,该函数可以生成该单词的广义缩写。
因此,如果输入像“word”,则输出将是 ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
为了解决这个问题,我们将遵循以下步骤:
定义一个数组 ret
定义一个函数 solve(),它将接收 s、idx,
如果 idx >= s 的大小,则:
将 s 插入 ret 的末尾
返回
y := 从索引 0 到 idx - 1 的 s 的子字符串
i := y 的大小
num := 空字符串
当 (i >= 0 且 y[i] <= '9' 的 ASCII 码 且 y[i] >= '0' 的 ASCII 码) 时,执行:
num := y[i] + num
(将 i 减 1)
如果 i 不等于 y 的大小,则:
ret := 从索引 (0 到 idx - (y 的大小 - 1 - i) - 1) 的 s 的子字符串连接 (number + 1) 作为字符串连接从索引 (0 到 idx) 的 s 的子字符串
s1 := num + 1 作为字符串
s2 := num 作为字符串
如果 s1 的大小与 s2 的大小相同,则:
否则
solve(ret, idx + 1)
否则
prev := s[idx]
s[idx] := '1'
solve(s, idx + 1)
s[idx] := prev
solve(s, idx + 1)
从主方法执行以下操作:
solve(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, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP