重新排列字符串

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:

例:

    Input:
    XY3BFA9KA2

    Output:
    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 map<char,int>m to tore characters of the string with respective frequencies;

    声明map <char,int> m以相应的频率撕裂字符串中的字符;

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

    重排部分:

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

Example with explanation:

带有说明的示例:

    Input:
    XY3BFA9KA2

    So,
    After processing :

    Map m becomes:
    Char(key)	Int(value)
    'A'	        2
    'B'	        1
    'F'	        1
    'K'	        1
    'X'	        1
    'Y'	        1

    Sum: 14

    Thus it prints:
    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 ++实现:

#include <bits/stdc++.h>
using namespace std;

void rearrange(string s){
	int sum=0;
	map<char,int> m;
	
	for(int i=0;i<s.length();i++){
		if(s[i]>='0' && s[i]<='9')//digut
			sum+=s[i]-'0';
		else //character
			m[s[i]]++;
	}

	for(auto it=m.begin();it!=m.end();it++){
		//print the character as many time it occured
		for(int i=0;i<it->second;i++)
			cout<<it->first;
	}
	cout<<sum<<endl; //printing sum
}

int main(){
	string s;

	cout<<"Enter input string\n";
	cin>>s;
	cout<<"Rearranged string is:\n";
	rearrange(s);

	return 0;
}

Output

输出量

Enter input string
XY3BFA9KA2
Rearranged string is:
AABFKXY14


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值