C++ 中的通用缩写

c++server side programmingprogramming更新于 2025/4/10 1:22:17

假设有一个单词。我们必须定义一个可以生成单词的通用缩写的函数。

因此,如果输入为"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 :=空白字符串

  • while (i >= 0 and y[i] <= '9' 的ASCII码和y[i] >= '0' 的ASCII码),执行−

    • num := y[i] + num

    • (decrease i by 1)

  • 如果 i 不等于 y 的大小,则 −

    • ret := s 的子字符串,从索引 (0 到 idx - (y 的大小 - 1 - i) - 1) 连接 (number + 1) 作为字符串 连接 s 的子字符串,从索引 (0 到 idx)

    • 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)

  • 从 main 方法执行以下操作 −

  • solve(word, 0)

  • return 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, ]

相关文章