第一个只出现一次的字符(Java实现)


import java.util.HashMap;

public class E50FirstNonredundantChar {
    //第一个不重复的字符
    /*问题一:字符串中第一个不重复的字符*/
    public static String getChar(String str){
        if (str == null || str.length() == 0)
            return null;

        final int SIZE = 256;
        HashMap<Character, Integer> hashMap = new HashMap<>(SIZE);
        char[] chars = str.toCharArray();
        //初始化
        for (int i = 0; i < SIZE; i ++)
            hashMap.put((char) i, 0);
        //统计字符串中字符出现的次数
        for (int i = 0; i < str.length(); i ++){
            hashMap.put(chars[i], hashMap.get(chars[i]) + 1);
        }
        //遍历找到第一次出现的不重复字符
        for (int i = 0; i < str.length(); i ++){
            if (hashMap.get(chars[i]) == 1)
                return String.valueOf(chars[i]);
        }
        return null;
    }

    /*问题二:字符流中第一个不重复的字符*/
    private int index;
    private int[] occurrence;
    private static final int SIZE = 256;

    public E50FirstNonredundantChar(){
        index = 0;
        occurrence = new int[SIZE];
        for (int i = 0; i < SIZE; i ++)
            occurrence[i] = -1;
    }

    public void insert(char c){
        int position = (int) c;
        if (occurrence[position] == -1)
            occurrence[position] = index;
        else if (occurrence[position] >= 0)
            occurrence[position] = -2;
        index ++;
    }

    public String getFirstNonredundantChar(){
        char goalChar = '\u0000';
        int minIndex = index;
        for (int i = 0; i < SIZE; i ++){
            if (occurrence[i] >= 0 && occurrence[i] < minIndex) {
                minIndex = occurrence[i];
                goalChar = (char) i;
            }
        }
        return String.valueOf(goalChar);
    }

    //测试用例
    public static void main(String[] args){
        String str = "acbfweacrte";
        System.out.println(E50FirstNonredundantChar.getChar(str));

        E50FirstNonredundantChar first = new E50FirstNonredundantChar();
        first.insert('a');
        first.insert('b');
        first.insert('a');
        first.insert('c');
        first.insert('b');
        System.out.println(first.getFirstNonredundantChar());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值