码迷,mamicode.com
首页 > 其他好文 > 详细

字符流中第一个不重复的字符-剑指Offer

时间:2016-07-21 21:52:58      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

题目描述

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

输入描述

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

思路

  1. 模拟一个哈希表,长度为256,索引为字符的编码,初始化为-1,第一次出现时把该字符出现的位置赋给该数组元素,第二次出现时赋给-2,说明已经不是只出现一次了。最后遍历数组,找到值非负的最小的元素的索引就是第一个只出现一次的字符,用(char)强转一下即可。

代码

public class Solution {
    int[] cArr = null;
	int index = 0;
	Solution() {
		cArr = new int[256];
		for (int i = 0; i < 256; i++) {
			cArr[i] = -1;
		}
	}
	//Insert one char from stringstream
    public void Insert(char ch)
    {
        if (cArr[ch] == -1) {
        	cArr[ch] = index;
        } else if (cArr[ch] >= 0) {
        	cArr[ch] = -2;
        }
        index++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    	int min = Integer.MAX_VALUE;
    	char ch = ‘#‘;
    	for (int i = 0; i < cArr.length; i++) {
    		if (cArr[i] >= 0 && cArr[i] < min) {
    			min = cArr[i];
    			ch = (char)i;
    		}
    	}
    	return ch;
    }
}

字符流中第一个不重复的字符-剑指Offer

标签:

原文地址:http://www.cnblogs.com/rosending/p/5693081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!