zoukankan      html  css  js  c++  java
  • 找出一个只出现一次的字符

    一,问题描述

    给定一个字符串,找出一个 其中只出现一次的字符

    如"abaccdeff" 只出现一次的字符有 'b'    'd'     'e'

    二,问题分析

    ①字符集是个常量 ,字符只有那么多。比如ASCII 一共256个,比如 字母表一共只有26个,再比如数字,一共0-9 只有10个

    ②出现一次,说明是次数。将字符映射成出现的次数----Map

    ③数组就是一种特殊的Map,数组的下标是不变的,相当于Key,下标 i 处存储的值就相当于Value

    比如,定义一个存储26个字母出现频率的int[], 下标0处存储 'a',下标1处存储 'b'  ..... 下标 [c-'a'] 处 存储 字符 c

    三,代码实现

     1 public class FindChar {
     2     public static char onceChar(String str){
     3         if(str == null)
     4             return '';
     5         int[] freq = new int[256];
     6         for(int i = 0; i < freq.length; i++)
     7             freq[i] = 0;
     8         for (int i = 0; i < str.length(); i++)
     9             freq[str.charAt(i)]++;
    10         for(int i = 0; i < freq.length; i++)
    11             if(freq[i] == 1)
    12                 return (char)i;
    13         return '';
    14     }
    15     
    16     public static void main(String[] args) {
    17         String str1 = "Abcde";
    18         String str2 = "aaBccddee";
    19         String str3 = "aabbccddee";
    20         
    21         char c1 = onceChar(str1);
    22         char c2 = onceChar(str2);
    23         char c3 = onceChar(str3);
    24         char c4 = onceChar(null);
    25         
    26         System.out.println("c1:" + c1 + " c2:" + c2 + " c3:" + c3 + " c4:" + c4);
    27     }
    28 }
  • 相关阅读:
    windows 按时自动化任务
    Linux libusb 安装及简单使用
    Linux 交换eth0和eth1
    I.MX6 GPS JNI HAL register init hacking
    I.MX6 Android mmm convenient to use
    I.MX6 GPS Android HAL Framework 调试
    Android GPS GPSBasics project hacking
    Python windows serial
    【JAVA】别特注意,POI中getLastRowNum() 和getLastCellNum()的区别
    freemarker跳出循环
  • 原文地址:https://www.cnblogs.com/hapjin/p/5511210.html
Copyright © 2011-2022 走看看