重新排列字符串

小鱼儿 2023-03-05 09:40 135阅读 0赞

Problem statement:

问题陈述:

Given a string containing uppercase alphabets and integer digits (from 0 to 9), the task is to print the alphabets in the order followed by the sum of digits.

给定一个包含大写字母和整数(从0到9)的字符串,任务是按字母的顺序打印,然后跟着数字的总和。

Example:

例:

  1. Input:
  2. XY3BFA9KA2
  3. Output:
  4. AABFKXY14

Solution

Problem can be easily solved with help of a map. (Read more: maps in C++ STL)

借助地图可以轻松解决问题。 (了解更多: C ++ STL中的地图)

Pre-requisite: Input string s

前提条件:输入字符串s

Algorithm:

算法:

  1. Declare sum=0 to add integers of the string.

    声明sum = 0以添加字符串的整数。

  2. Declare mapm to tore characters of the string with respective frequencies;

    声明map m以相应的频率撕裂字符串中的字符;

  3. For i=0:s.length()-1
    1. IF(s[i]>='0' && s[i]<='9') //current character is digit
    2. sum+=s[i]-'0'; //add to sum//s[i]-'0'=actual numeric value
    3. Else //it's a alphabetical character
    4. m[s[i]]++; //store character with its frequency
    5. END IF
    END FOR
  4. Rearranging part:

    重排部分:

    1. For iterator it=m.begin():m.end()-1
    2. //inner loop to print the character as many times it occurs
    3. For i=0 : it->second-1 //it->second is the frequency of character it->first
    4. Print it->first;
    5. END FOR
    6. END FOR
    7. Print sum;

Example with explanation:

带有说明的示例:

  1. Input:
  2. XY3BFA9KA2
  3. So,
  4. After processing :
  5. Map m becomes:
  6. Char(key) Int(value)
  7. 'A' 2
  8. 'B' 1
  9. 'F' 1
  10. 'K' 1
  11. 'X' 1
  12. 'Y' 1
  13. Sum: 14
  14. Thus it prints:
  15. AABFKXY14

Note: The map is always sorted according to its key. Thus, here we don’t need to take any additional care for maintain alphabet order as the map itself is always sorted as per its key (character here).

注意: 映射始终根据其键进行排序。 因此,由于地图本身始终按其键(此处为字符)进行排序,因此在这里无需额外注意保持字母顺序。

C++ implementation:

C ++实现:

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void rearrange(string s){
  4. int sum=0;
  5. map<char,int> m;
  6. for(int i=0;i<s.length();i++){
  7. if(s[i]>='0' && s[i]<='9')//digut
  8. sum+=s[i]-'0';
  9. else //character
  10. m[s[i]]++;
  11. }
  12. for(auto it=m.begin();it!=m.end();it++){
  13. //print the character as many time it occured
  14. for(int i=0;i<it->second;i++)
  15. cout<<it->first;
  16. }
  17. cout<<sum<<endl; //printing sum
  18. }
  19. int main(){
  20. string s;
  21. cout<<"Enter input string\n";
  22. cin>>s;
  23. cout<<"Rearranged string is:\n";
  24. rearrange(s);
  25. return 0;
  26. }

Output

输出量

  1. Enter input string
  2. XY3BFA9KA2
  3. Rearranged string is:
  4. AABFKXY14

翻译自: https://www.includehelp.com/icp/rearrange-a-string.aspx

发表评论

表情:
评论列表 (有 0 条评论,135人围观)

还没有评论,来说两句吧...

相关阅读