C++ 字符串排序并计算整数和
讨论一个问题,将字母字符串按排序顺序重新排列,并添加字符串中存在的所有整数,例如
Input : str = “adv4fc3” Output : “ acdfv7” Explanation: all the letters have been sorted to “acdfv” followed by the sum of integers 4 and 3. Input: str = “ h2d7e3f ” Output: “ defh12” Explanation: all the letters have been sorted to “defh” followed by the sum of integers 2, 7, and 3.
解决方案方法
在这个问题中,我们需要执行两个任务,一个是排序字符串,另一个是添加整数。
可以通过统计字符串中每个字母出现的次数,然后根据其次数形成一个新字符串来完成字符串的排序。
我们可以通过每次遇到整数时将其添加到一个变量中来进行整数的加法。
示例
上述方法的 C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
int main(){
string str = "h2d7e3f";
int ch[26] = {0};
int count = 0;
// traverse through all the characters of string.
for (int i = 0; i < str.length(); i++){
// keeping count of occurance every character.
if (str[i]>='a' && str[i] <='z')
ch[str[i] - 97] = ch[str[i] - 97] + 1;
// If an Integer encounters.
else
count = count + (str[i]-'0');
}
string final = "";
// Making a sorted string with the help of ch array.
for (int i = 0; i < 26; i++){
char a = (char)('a'+i);
// insert the current character
// to new string untill it count ends
while (ch[i]-- != 0)
final = final + a;
}
// and finally insert sum of all integers in the string.
if (count>0)
final = final + to_string(count);
cout << "Rearranged string: " << final;
return 0;
}输出
Rearranged string: defh12
上述代码的解释
数组 ch 初始化为大小 26,因为我们需要保留 26 个字母出现次数的计数。
在第一个循环中,我们遍历字符串。对于每个字母,我们都会增加该字母的计数。对于每个整数,我们都会将其添加到 count 变量中。
在第二个循环中,我们根据所有计数形成一个新的排序字符串,其中我们根据其计数将字符附加到字符串中。
最后,我们将字符串与我们在第一个循环中计算出的整数的总和附加在一起。
结论
在本教程中,我们讨论了如何按排序顺序排列字符串,并根据哈希表方法解决了一个基于此的问题。我们还讨论了此问题的 C++ 代码。我们可以用其他任何编程语言(如 C、Java、Python 等)编写。希望本教程对您有所帮助。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP