微软算法100题17 字符串中找到第一个只出现一次的字符

第17 题:
题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b

思路:要找出只出现一次的字符,很明显需要统计所有字符出现的次数,然后找出次数为一的那一个,统计次数最先想到的是hashTable,但此题有更好的办法,因为每个char其实对应一个唯一的ASCII值,所以可以构造一个包含所有字符ASCII值的int数组,来映射字符与出现次数的关系,同时一个char是8个字节,总共有256个可能,所以该数组的大小应为256

 1 package com.rui.microsoft;
 2 
 3 public class Test17_CharStatistics {
 4 
 5     public static void main(String[] args) {
 6         String orig = "abaccdeff";
 7         char res = find(orig);
 8         System.out.println(res);
 9     }
10     
11     public static char find(String s){
12         char res = 0;
13         
14         int[] in = new int[256];
15         
16         for(int i = 0; i < s.length(); i++){
17             char tmp = s.charAt(i);
18             in[tmp]++;
19         }
20         int start = 0;
21         for(; start<in.length; start++){
22             if(in[start] == 1)break;;
23         }
24         res = (char)start;
25         return res;
26     }
27 
28 }
原文地址:https://www.cnblogs.com/aalex/p/4905946.html