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

剑指offer:字符流中第一个不重复的字符

时间:2020-05-07 17:04:05      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:vat   tap   appear   length   空字符串   不重复   offer   first   出现   

题意描述

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

输出描述

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

解题思路

一、思路一

    public class Solution {
        //对输入流的字符进行拼接
        //切记初始化为空字符串,如果不初始化的话,s = ‘null‘ + ‘ch‘,会对统计的结果产生影响
        private String s = "";
        
        //将输入的字符对应到char数组中,索引值就是字符出现的次数
        private char[] chars = new char[128];

        //Insert one char from stringstream
        public void Insert(char ch) {
            s += ch;
            chars[ch]++;
        }
        //return the first appearence once char in current stringstream
        public char FirstAppearingOnce() {
            //遍历当前字符串,如果当前字符在数组中索引值为1,返回字符
            for (int i = 0; i < s.length(); i++) {
                if (chars[s.charAt(i)] == 1) {
                    return s.charAt(i);
                }
            }
            return ‘#‘;
        }
    }

剑指offer:字符流中第一个不重复的字符

标签:vat   tap   appear   length   空字符串   不重复   offer   first   出现   

原文地址:https://www.cnblogs.com/le-le/p/12844084.html

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