【劍指Offer】54字符流中第一個不重複的字符

題目描述

請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符「google"時,第一個只出現一次的字符是"l"。python

輸出描述:數組

若是當前字符流沒有存在出現一次的字符,返回#字符。函數

時間限制:1秒;空間限制:32768K;本題知識點:字符串google

解題思路

用一個足夠大的數組來記錄對應ascii碼值的字符出現的次數,再判斷字符流中第一個不重複的字符。code

Python代碼:utf-8

# -*- coding:utf-8 -*-
class Solution:
    # 返回對應char
    def __init__(self):
        self.s = [0]*256 #ascii碼錶記錄出現次數
        self.l='' #記錄輸入字符流
    def FirstAppearingOnce(self):
        # write code here
        for i in self.l:
            if self.s[ord(i)] == 1: #僅出現一次
                return i
        return '#'
    def Insert(self, char):
        # write code here
        self.l = self.l + char
        self.s[ord(char)] += 1
相關文章
相關標籤/搜索