C++ 通过删除重复出现的内容来解码给定字符串
本文的目的是实现一个程序,通过删除重复出现的内容来解码给定的字符串。
正如您所知,字符串就是一系列字符的集合。在字符串中,字符的重复次数没有限制。一个字符串中可以多次出现相同的字符。本文将找出一种方法,通过删除重复出现的内容来解码给定的编码字符串str。
我们的目标是解码所提供的字符串str,其中’a’只出现一次,’b’出现两次,’c’出现三次,’d’出现四次,继续到’z’出现26次。
问题陈述
实现一个程序,通过删除重复出现的内容来解码给定的字符串。
注意 − 不要忽略字母中可能包含的空格。
示例1
Let us take the input string str = “abbbb accc”
The output obtained is: abb ac
解释
每个字母的出现次数与英文字母表有关。结果字符串是”abb acc”,因为这里字母b重复了四次,字母a重复了两次,最后字母c重复了三次。
同样,在这个示例中,空格不会被忽略。
示例2
Let us take the input string str = “ddddadddd”
The output obtained is: dad
解释
每个字母都是根据它在英文字母表中出现的次数编写的。结果字符串是”dad”,因为这里字母d重复出现了八次,最后字母a只出现了一次。
此外,在这种情况下,字符之间没有空格。
示例3
Let us take the input string str = “abbccc”
The output obtained is: abc
解释
每个字母在英文字母表中出现的次数写在心里。结果字符串是 “abc”,因为这里字母 a 只出现一次。字母 b 出现两次,最后字母 c 出现三次。
此外,在这种情况下,字符之间没有空格。
方法
为了通过删除重复出现来解码给定的字符串,我们在本文中应用了以下方法。
解决这个问题和解码给定字符串的方法是基于迭代字符串。
也就是说,通过迭代字符串 str 并将每个字符推送到输出字符串之前,在向前查找下一个字符的位置之前,可以解决所述问题。
步骤
打印给定字符串中驼峰字符的数量的算法如下所示
要解决这个问题,请遵循以下列表中列出的指示 –
- 步骤1 - 开始
-
步骤2 - 定义字符串
-
步骤3 - 创建一个名为 result 的变量,其初始值为空字符串,以存储输出字符串。
-
步骤4 - 创建名为 findOccurences(char a1) 的函数,并执行以下操作 –
-
步骤5 - 如果 a1 的值在 a 和 z 之间,则将 a1 的值返回为 ‘a’。如果 a1 的值范围不是 A 到 Z,则将 a1 的值返回为 ‘Z’。否则,返回0。
-
步骤6 - 定义函数 decodeTheString(string s) 来解码字符串 s
-
步骤7 - 在完成上述阶段后,打印字符串结果为最终字符串。
-
步骤8 - 停止
示例: C++ 程序
这是上述编码的 C++ 程序实现,通过删除重复出现来解码给定字符串。
// C++ program for our above algorithm
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of occurences of each character
int findOccurences(char a1){
// If the character is a lower case , that is [a-z]
if (a1 <= 'z' && a1 >= 'a') {
return a1 - 'a';
}
// If the character is an uppercase, that is [A-Z]
else if (a1 <= 'Z' && a1 >= 'A') {
return a1 - 'A';
}
// If the character is something else like a punctuation mark then
return 0;
}
// Function used for decoding the given string str
void decodeTheString(string s){
string result = "";
// Iterate through the provided string str
for (int i = 0; i < s.length(); i++) {
result.push_back(s[i]);
// Find the index i of the next characterto be printed
i += findOccurences(s[i]);
}
cout << "The decoded string: " << result << endl;
}
int main(){
string s = "aaabbbb";
cout << "Input string: "<< s << endl;
decodeTheString(s);
return 0;
}
输出
Input string: aaabbbb
The decoded string: aaabb
结论
同样地,我们可以通过从字符串中删除重复出现的字符来解码任意给定的字符串。
本文解决了通过从任意给定字符串中删除重复出现的字符来解码的挑战。提供了C++编程代码以及解码任意给定字符串的算法。