字符流中第一个不重复的字符

来源:互联网 发布:数据库安全管理规定 编辑:程序博客网 时间:2024/05/21 06:27

直接代码:

package TestProblem;public class Test55 {/**     * 题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。     */private static class CharStatistics{//出现一次的标识private int index=0;private int[] occurrence = new int[256];public CharStatistics(){for (int i = 0; i < occurrence.length; i++) {occurrence[i]=-1; //默认初始全为-1}}private void Insert(char ch){if(ch>255){throw new IllegalArgumentException(ch+"must be a ASCII char");}//只出现一次if(occurrence[ch]==-1){occurrence[ch]=index;//index记录字符串中的位置}else{//出现两次occurrence[ch]=-2;}index++;}public char firstAppearingOnce(String data){if (data == null) {                throw new IllegalArgumentException(data);            }for (int i = 0; i < data.length(); i++) {Insert(data.charAt(i));}//在对应的哈希表完了之后进行统计char ch='\0';//用于记录最小的索引,对应的就是第一个不重复的数字int minIndex=Integer.MAX_VALUE;for (int i = 0; i < occurrence.length; i++) {//遍历一遍数组if(occurrence[i]>=0 &&occurrence[i]<minIndex){ch=(char)i;minIndex=occurrence[i];//找到最小的值主要是minIndex在不断的更新}}return ch;}}public static void main(String[] args) {//   System.out.println(new CharStatistics().firstAppearingOnce("")); // '\0'//        System.out.println(new CharStatistics().firstAppearingOnce("g")); // 'g'//        System.out.println(new CharStatistics().firstAppearingOnce("go")); // 'g'//        System.out.println(new CharStatistics().firstAppearingOnce("goo")); // 'g'//        System.out.println(new CharStatistics().firstAppearingOnce("goog")); // '\0'//        System.out.println(new CharStatistics().firstAppearingOnce("googl")); // l        System.out.println(new CharStatistics().firstAppearingOnce("google")); // l}}


0 0