每日一道算法题 字符个数统计

题目

字符个数统计_牛客题霸_牛客网 (nowcoder.com)

c语言

建立一个全为0的ascii[128],若字符的ascii码为a,就令ascii[a]=1

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[501];
    int ascii[128]={0};
    scanf("%s",str);
    for(int i=0;i<strlen(str);i++)
    {
        ascii[str[i]]=1;

    }

    int count=0;

    for(int i=0;i<128;i++)
    {
        if(ascii[i]==1)
        count++;
    }

    printf("%d",count);

    return 0;
}

c++

使用set,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序。

#include <iostream>
#include <set>
using namespace std;
int main(void)
{
	set<int> mySet = {1,2,3};  //初始化

	cout << mySet.size() << endl; //3
	cout << mySet.empty() << endl; //false

	mySet.insert(4);  
	mySet.insert(4); //重复的不会插入
	for (int e : mySet)
		cout << e;  //1234
	cout << endl;

	/*clear(); 清除 set中的所有元素。
	erase(pos); 删掉迭代器 pos 所指向的元素,并返回指向下一个元素的迭代器。*/
	/*find(key); 在 set  中查找键 key。
	如果找到,返回指向该键的元素的迭代器;否则返回 end() 迭代器。*/
	auto it = mySet.find(3); //查找3的迭代器
	if (it != mySet.end())
		it = mySet.erase(it); // 删除元素3,it现在指向4 
	return 0;
}
#include <iostream>
#include <set>
using namespace std;

int main(void)
{
    string str;
    cin>>str;
    
    set<char> se;
    for(char c: str)
    {
        se.insert(c);

    }

    cout<<se.size();
    return 0;
}

python

使用Counter,其主要功能:可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。

from collections import Counter

list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]
dic = Counter(list1)
print(dic)
#Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})

print(dict(dic))
#按字母顺序排序的
#{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}

print(dic.items()) #dic.items()获取字典键值对
#按字母顺序排序的
#dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])

print(dic.keys())
#dict_keys(['a', 'b', 'c', 'f', 'g'])

print(dic.values())
#dict_values([3, 1, 2, 2, 3])

print(sorted(dic.items(), key=lambda s: (-s[1])))
#按统计次数降序排序
#[('a', 3), ('g', 3), ('c', 2), ('f', 2), ('b', 1)]

for i, v in dic.items():
    if v == 1:
        print(i)
#结果:
#b
from collections import Counter


str=input()

cnt=Counter(str)

print(len(cnt))

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值