解碼給定字串,去除重複出現的內容
本文旨在實現一個程式,用於解碼給定字串,去除重複出現的內容。
正如你所知,字串只是一系列字元的集合。字串中字元的重複次數沒有限制。一個字串可以包含多次出現的相同字元。我們將找到一種方法來解碼給定的編碼字串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 − 完成上述步驟後,列印字串result作為最終字串。
步驟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++程式設計程式碼以及解碼任何給定字串並去除重複出現的內容的演算法。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP