HJ10 字符个数统计

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

题目描述:

image-20230110182121150

示例:

image-20230110182223459

思路:

方法一:

ASCII码范围在0~127,范围较小,借助辅助数组空间Helper:

  1. 遍历字符串,令Helper[出现字符ASCII码]++,记录已出现字符

  2. 再遍历辅助数组Helper,若不为0即表示该下标所示字符出现过,进行计数。

方法二:

也可以使用Java的HashSet,遍历每个字符,添加到HashSet中(HashSet可以去重),最后输出HashSet的大小。

具体实现:

方法一:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int[] helper = new int[128];
        int cnt = 0;
        for(int i = 0; i < s.length(); i++)
            helper[s.charAt(i)]++;
        for(int i = 0; i < helper.length; i++)
            if(helper[i] != 0) cnt++;
        System.out.println(cnt);
    }
}

方法二:

import java.util.Scanner;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        HashSet<Character> helper = new HashSet<>();
        for(int i = 0; i < s.length(); i++)
            helper.add(s.charAt(i));
        System.out.println(helper.size());
    }
}

时间复杂度:

都是O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值