博客
关于我
华为机试: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/

你可能感兴趣的文章
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>