皮皮的LeetCode刷题库

【剑指Offer】054——字符流中第一个不重复的字符 (字符串

2019-08-22  本文已影响0人  就问皮不皮

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。如果当前字符流没有存在出现一次的字符,返回#字符。

解题思路

用一个哈希表来存储每个字符及其出现的次数,另外用一个字符串 s 来保存字符流中字符的顺序。

参考代码

Java

import java.util.HashMap;
public class Solution {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    StringBuffer s = new StringBuffer(); // 字符流
    //Insert one char from stringstream
    public void Insert(char ch){
        s.append(ch);
        // 统计输入的字符
        if(map.containsKey(ch)){
            map.put(ch, map.get(ch)+1);
        }else{
            map.put(ch, 1);
        }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        for(int i = 0; i < s.length(); i++){
            if(map.get(s.charAt(i)) == 1)
                return s.charAt(i);
        }
        return '#';
    }
}

Python

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.tmap = {}
        self.s = ""
    # 返回对应char
    def FirstAppearingOnce(self):
        # write code here
        for i in range(len(self.s)):
            if self.tmap[self.s[i]] == 1:
                return self.s[i]
        return '#'
    def Insert(self, char):
        # write code here
        self.s +=  char
        if char in self.tmap.keys():
            self.tmap[char] = self.tmap[char] + 1
        else:
            self.tmap[char] = 1

个人订阅号

image
上一篇 下一篇

猜你喜欢

热点阅读