题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。




题目链接:
https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking





package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class A54_FirstAppearingOnce {

    @Test
    public void test() {
        Insert('g');
        Insert('o');
        Insert('o');
        Insert('g');
        Insert('l');
        System.out.println(FirstAppearingOnce());
    }

    Map<Character, Integer> ans = new HashMap<>();
    int pos = -1;

    //Insert one char from stringstream
    public void Insert(char ch) {
        pos++;
        if (ans.containsKey(ch)) {
            ans.put(ch, -1);
        } else {
            ans.put(ch, pos);
        }
    }

    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        int pos = -1;
        char c = '#';
        Set<Map.Entry<Character, Integer>> entries = ans.entrySet();
        Iterator<Map.Entry<Character, Integer>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Character, Integer> next = iterator.next();
            if (next.getValue() != -1 && (pos == -1 || next.getValue() < pos)) {
                pos = next.getValue();
                c = next.getKey();
            }
        }
        return c;
    }


}

 

posted on 2019-10-08 15:30  MoonBeautiful  阅读(118)  评论(0编辑  收藏  举报