zoukankan      html  css  js  c++  java
  • 字符流中第一个不重复的字符 python实现

    题目描述

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

    输出描述:

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

    ## 思路

    用两个列表,一个用来保存所有的字符,一个用来保存只出现一次的字符,


    算法

    # -*- coding:utf-8 -*-
    class Solution:
        # 返回对应char
        def __init__(self):
            self.array=[] #保存出现的所有字符
            self.result=[] # 保存只出现一次的字符
        def FirstAppearingOnce(self):
            # write code here
            if len(self.result)!=0:
                for i in self.result:
                    return i
            return '#'
        def Insert(self, char):
            # write code here
            for i in char:
                # 如果已经出现一次的字符再次出现,则将该字符从只出现一次的列表中去除
                if i in self.result:
                    self.result.remove(i)
                # 如果没出现在result列表,野没出现在array的列表,才能加入result列表,
                # 这里是考虑排除出现奇数个相同字符的情况,
                elif i not in self.array:
                    self.result.append(i)
                self.array.append(i)
    
  • 相关阅读:
    leetcode--Longest Valid Parentheses
    leetcode--Sum Root to Leaf Numbers
    leetcode--Max Points on a Line
    leetcode--Substring with Concatenation of All Words
    leetcode--Restore IP Addresses
    leetcode--4Sum
    leetcode--3Sum
    leetcode--Simplify Path
    leetcode--Text Justification
    leetcode--Multiply Strings
  • 原文地址:https://www.cnblogs.com/Dandelion-L/p/11223106.html
Copyright © 2011-2022 走看看