Loading...

《剑指Offer》面试题55:字符流中第一个不重复的字符

思路:
1.使用一个容器保存字符的当前下标,所有字符下标初始为0,插入的时候,如果判断这个字符下标数组不为0,则表明字符已经出现过,直接将数组置为1即可,否则则置为当前index值,并且index++,时间复杂度为O(1);
2.查找第一不重复字符时,循环判断整个容器数组保存的值,找出index值最小的一个数据,即为最先插入的字符。时间复杂度为O(256),因为256为常数,即复杂度也为O(1);

package com.test20160710;

import java.util.Stack;

/**
 * Created by yan on 2016/7/10.
 */
public class FirstAppearingOnce {

    int count[] = new int[256];
    int index = 1;
    //Insert one char from stringstream
    public void Insert(char ch)
    {
       if(count[ch]==0){
           count[ch] = index++;
       }else {
           count[ch] = -1;
       }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        int temp = Integer.MAX_VALUE;
        char ch = '#';
        for(int i=0;i<256;i++){
            if(count[i]!=0&&count[i]!=-1&&count[i]<temp){
                temp = count[i];
                ch = (char) i;
            }
        }
        return ch;
    }
}
posted @ 2016-07-10 13:14  严康  阅读(164)  评论(0编辑  收藏  举报