首页 > 试题广场 >

字符串归一化

[编程题]字符串归一化
  • 热度指数:15628 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
通过键盘输入一串小写字母 (a~z) 组成的字符串。
请编写一个字符串归一化程序,统计字符串中相同字符出现的次数,并按字典序输出字符及其出现次数。
例如字符串"babcc"归一化后为"a1b2c2"

数据范围:输入的字符串长度满足 ,保证输入中仅包含小写的英文字母

输入描述:
每个测试用例每行为一个字符串,以'\n'结尾,例如cccddecca


输出描述:
输出压缩后的字符串ac5d2e
示例1

输入

dabcab

输出

a2b2c1d1
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        char[] chars=sc.nextLine().toCharArray();
        //经验,一般是用hashmap来统计出现次数的,
        //但本题是对字符统计次数,可以专门用一个counts数组来统计次数
        int[] counts=new int[26];
        for(int i=0;i<chars.length;i++){
            counts[chars[i]-'a']++;
        }
        for(int i=0;i<26;i++){
            char c=(char)('a'+i);
            int count=counts[i];
            if(count==0){
                continue;
            }else{
                System.out.print(c+""+count);
            }
        }
    }
}

发表于 2019-08-05 21:59:53 回复(0)
string = input()
for i in sorted(list(set(string))):
    item = string.count(i)
    print(i + str(item), end = '')

发表于 2019-10-10 22:00:53 回复(2)
#include<iostream>
#include<string>
using namespace std;
int main(){
    int count[26] = {0};   //记录每个字母的个数
    string s;
    cin >> s;
    for(int i = 0; i < s.length(); i++){
        count[s[i]-'a']++;
    }
    char c = 'a';
    for(int i = 0; i < 26; i++){
        if(count[i]){
            cout << c << count[i];
        }
        c++;
    }
    cout << endl;
    return 0;
}

发表于 2019-09-03 23:03:31 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    while(cin>>s)
    {
        sort(s.begin(),s.end());
        string res="";
        int n=1;
        cout<<s[0];
        for(int i=1;i<s.size();i++)
        {
            if(s[i]==s[i-1])
                n++;
            else
            {
                cout<<n;
                cout<<s[i];
                n=1;
            }
        }
        cout<<n<<endl;
    }
    return 0;
}

发表于 2019-06-30 18:55:06 回复(0)
发表于 2018-11-07 15:49:16 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
while(cin>>s){
int l = s.length();
int cnt[26] = {0};
for(int i=0;i<l;i++)
cnt[s[i]-'a']++;
for(int i=0;i<26;i++){
if(cnt[i]>=1)
cout<<char('a'+i)<<cnt[i];
}
cout<<endl;
}
return 0;
}

发表于 2019-07-07 22:55:35 回复(0)
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
using namespace std;
int main(){
    char ch;
    map<char,int> m;
    while(cin>>ch){
        m[ch]++;
    }
    map<char,int>::iterator it;
    for(it=m.begin();it!=m.end();it++){
        cout<<it->first<<it->second;
    }cout<<endl;
    return 0;
}

编辑于 2020-04-13 14:46:28 回复(0)
Java解法
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] count = new int[256];
        String s = scanner.nextLine();
        char[] array = s.toCharArray();
        for (char c : array) {
            count[c]++;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 'a'; i <= 'z'; i++) {
            if (count[i]!=0){
                builder.append((char)i);
                if (count[i]!=1)
                    builder.append(count[i]);
            }
        }
        System.out.println(builder.toString());
    }
}


发表于 2020-03-01 20:03:35 回复(0)
#include<iostream>
using namespace std;

const int SIZE = 128;
int main()
{
    
    int num[26] = {0};             //26个字母
    char buf[SIZE];                //定义输入字符的buf大小
    fgets(buf,SIZE,stdin);          //键盘输入
    int i = 0;
    while(buf[i]!='\n')            //循环检测相同的字母
    {
        ++num[buf[i++]-'a'];       //检测到相同的字母,++操作
        if(i==SIZE)            // 考虑输入太多的字母的条件
        {
            i = 0;
            fgets(buf,SIZE,stdin);
        }

    }
    i = 0;
    while(i<26)                 //循环输出
    {
        if(num[i]!=0)        //判断字母存在不,没有则不用输入
        {
            //printf("%c%d",i+'a',num[i]);
            char p;
            p = i+'a';     //按照字符的顺序输出
            cout<<p<<num[i];    
        }
        ++i;
    }
    cout<<endl;
    return 0;
        
}

发表于 2019-10-09 17:30:40 回复(0)
#include <iostream>
#include <string>
using namespace std;
int main()
{     int a[26] = { 0 };     string str;     cin >> str;     for (int i = 0; i < str.size(); i++)     {         a[str[i] - 'a']++;     }
    char ch = 'a';
    for(int j = 0;j<26;j++)
    {
        if(a[j])
            cout << ch << a[j];
        ch++;
    }     return 0;
}
编辑于 2019-10-07 21:34:59 回复(0)
#include<iostream>
#include<string>
#include<map>

using namespace std;

int main(){
    string s;
    getline(cin,s);
    map<char,int> m;//map自动排序
    for(int i=0;i<s.length();i++){
        m[s[i]]++;
    }
    auto it=m.begin();
    while(it!=m.end()){
        cout<<it->first<<it->second;
        it++;
    }
    return 0;
}
发表于 2019-08-23 20:02:20 回复(2)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Solution6_字符串归一化 {

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        //存储每个字母出现的次数,0~a,1~b
        int[] nums = new int[26];
        for (int i = 0; i < str.length(); i++) {
            nums[str.charAt(i) - 'a']++;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 26; i++) {
            if (nums[i] > 0) sb.append((char) (i + 'a')).append(nums[i]);
        }
        System.out.println(sb.toString());
    }
}
发表于 2019-08-03 19:57:30 回复(0)
"""
使用Counter计数器
"""
import sys
import collections

if __name__ == "__main__":
    # sys.stdin = open("input.txt", "r")
    s = input().strip()
    obj = collections.Counter(s)
    d = sorted(obj.items(), key=lambda c: c[0])
    ans = ""
    for i in range(len(d)):
        ans += str(d[i][0]) + str(d[i][1])
    print(ans)

发表于 2019-07-06 21:25:13 回复(0)

import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str = sc.nextLine();
int [] array=new int [26];
for (int i = 0; i < str.length(); i++)
array[str.charAt(i)-'a']++;
for (int i = 0; i < 26; i++)
{
if(array[i]>=1)
System.out.print((char)('a'+i));
if(array[i]>1)
System.out.print(array[i]);
}
}

}


编辑于 2019-07-11 17:00:37 回复(0)
fromcollections importCounter
 
s =input()
 
c =Counter(s)
 
ans =''
fork insorted(c.keys()):
    ans +=k
    ans +=str(c[k])
 
print(ans)

发表于 2019-03-30 14:30:40 回复(1)
n = input()
n_dict = {}
for i in n:
    if i not in n_dict:  # 若dict中不包含此元素
        n_dict.update({i: 1})  # 将元素以 {元素:出现次数} 的格式,添加到dict中
    else:
        n_dict[i] += 1  # 若存在元素,则将对应元素的出现次数+1

# 格式化输出
res_list = []
for i in n_dict:
    res_list.append(str(i) + str(n_dict[i]))
res_list.sort()
for i in res_list:
    print(i, end='')  # 输出不换行

发表于 2019-09-20 15:52:28 回复(0)
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', function (line) {
    const arr = line.split('').sort();
    let obj:object={}
    let str=''
    for(let i=0;i<arr.length;i++){
        if(obj[arr[i]]){
            obj[arr[i]]++
        }else{
            obj[arr[i]]=1
        }
       
    }
    console.log(Object.entries(obj).map(v=>v.join('')).join(''))
   
});
编辑于 2024-01-04 22:49:09 回复(0)
#include <stdio.h>
#include <string.h>
int main() {
    char buf[1000000];
    int hash[26]={0};
    int i;
    scanf("%s",buf);
    for(i=0;i<strlen(buf);i++)
    {
        hash[buf[i]-'a']++;
    }
    for(i=0;i<26;i++)
    {
        if(hash[i]){
        printf("%c%d",i+'a',hash[i]);
        }
    }
    return 0;
哈希!
发表于 2023-05-06 21:25:10 回复(0)
package main

import (
    "fmt"
    "strconv"
)

func main() {
    var s string
    fmt.Scan(&s)
    cnt:=[26]int{}
    for _,ch:=range []byte(s){
        cnt[ch-'a']++
    }
    ans:=""
    for i,x:=range cnt{
        if x!=0{
            ans+=string(i+'a')+strconv.Itoa(x)
        }
    }
    fmt.Print(ans)
}

发表于 2023-03-11 19:53:04 回复(0)
#include <iostream>
using namespace std;

int main() {
    string s, res;
    cin >> s;
    int a[26] = {};
    for(char c : s)
        a[c - 'a']++;
    for(int i = 0; i < 26; i++){
        if(a[i] > 0){
            res += i + 'a';
            string temp;
            while(a[i]){
                char t = a[i] % 10 + '0';
                temp = t + temp;
                a[i] /= 10;
            }
            res += temp;
        }
    }
    cout << res;
    return 0;
}

发表于 2023-01-03 18:59:23 回复(0)