博客
关于我
华为机试:10. 字符个数统计
阅读量:383 次
发布时间:2019-03-05

本文共 1068 字,大约阅读时间需要 3 分钟。

编写一个函数,计算字符串中含有的不同字符的个数。字符在ASCII码范围内(0~127),换行表示结束符,不算在字符里。不在范围内的字符不作统计。多个相同的字符只计算一次。

输入

输入N个字符,字符在ASCII码范围内。

输出

输出范围在(0~127)字符的个数。

示例

输入abc输出3

实现方法

方法1

  • 思路

  • 初始化一个集合用于存储字符串中的不重复的字符。
  • 遍历字符串,对于每个字符:
    • 检查字符是否在ASCII码范围(0~127)内。
    • 如果不在范围内,跳过。
    • 如果在范围内,检查集合中是否存在该字符。
    • 如果不存在该字符,将其添加到集合中。
  • 返回集合的大小,即为不同字符的个数。
  • 实现

    import java.util.HashSet;import java.util.Set;public class Main {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        while (input.hasNext()) {            String str = input.nextLine();            System.out.println(countChar(str));        }    }    public static int countChar(String str) {        Set
    set = new HashSet<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 0 && c <= 127) { if (!set.contains(c)) { set.add(c); } } } return set.size(); }}

    注意:以上代码使用HashSet来存储字符,确保每个字符只存储一次。countChar函数遍历字符串的每个字符,检查字符是否在ASCII范围内,并且是否已经存在于集合中。如果满足条件,则将字符添加到集合中。最后,集合的大小即为不同字符的个数。

转载地址:http://wpjwz.baihongyu.com/

你可能感兴趣的文章
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>