📜  字符串的字母数字缩写

📅  最后修改于: 2022-05-13 01:57:08.982000             🧑  作者: Mango

字符串的字母数字缩写

给定一个长度小于 10 的字符串。我们需要打印该字符的所有字母数字字符串。

字母数字缩写是字符与数字混合的形式,数字等于所选子字符串的跳过字符数。因此,每当跳过字符的子字符串时,您必须将其替换为表示子字符串中字符数的数字。一个字符串可能有任意数量的跳过子字符串。没有两个子串应该彼此相邻。因此,结果中没有两个数字是相邻的。有关更清晰的想法,请参阅示例。

例子:

Input : ANKS 
Output :
ANKS (nothing is replaced)
ANK1 (S is replaced) 
AN1S (K is replaced)
AN2  (KS is replaced)
A1KS (N is replaced)
A1K1 (N and S are replaced)
A2S (NK is replaced)
A3 (NKS is replaced)
1NKS (A is replaced)
1NK1 (A and S are replaced)
1N1S (A and N is replaced)
1N2 (A and KS are replaced)
2KS (AN is replaced)
2K1 (AN and S is replaced)
3S (ANK is replaced)
4 (ANKS is replaced)

Input : ABC
Output : 
ABC
AB1 
A1C 
A2 
1BC 
1B1 
2C 
3
Note: 11C is not valid because no two digits should be adjacent, 
2C is the correct one because AB is a substring, not A and B individually

来源:谷歌面试问题

这个想法是从空字符串开始。在每一步,我们都有两个选择。

  1. 考虑字符。
  2. 添加字符以计数。如果没有计数,则使用 1。

无法加载图像

您可以看到每个字符如何作为字符或作为数字累加到结果中。这进一步在末尾产生 2^n 缩写,其中 n 是字符串的长度。

// C++ program to print all Alpha-Numeric Abbreviations
// of a String
#include 
using namespace std;
  
// Recursive function to print the valid combinations
// s is string, st is resultant string
void printCompRec(const string& s, int index,
                  int max_index, string st)
{
    // if the end of the string is reached
    if (index == max_index) {
        cout << st << "\n";
        return;
    }
  
    // push the current character to result
    st.push_back(s[index]);
  
    // recur for the next [Using Char]
    printCompRec(s, index + 1, max_index, st);
  
    // remove the character from result
    st.pop_back();
  
    // set count of digits to 1
    int count = 1;
  
    // addition the adjacent digits
    if (!st.empty()) {
  
        if (isdigit(st.back())) {
  
            // get the digit and increase the count
            count += (int)(st.back() - '0');
  
            // remove the adjacent digit
            st.pop_back();
        }
    }
  
    // change count to a character
    char to_print = (char)(count + '0');
  
    // add the character to result
    st.push_back(to_print);
  
    // recur for this again [Using Count]
    printCompRec(s, index + 1, max_index, st);
}
  
// Wrapper function
void printComb(std::string s)
{
    // if the string is empty
    if (!s.length())
        return;
  
    // Stores result strings one one by one
    string st;
  
    printCompRec(s, 0, s.length(), st);
}
  
// driver function
int main()
{
    string str = "GFG";
    printComb(str);
    return 0;
}

输出:

GFG 
GF1 
G1G 
G2 
1FG 
1F1
2G 
3

资料来源:职业杯