zoukankan      html  css  js  c++  java
  • 剑指offer 面试50题

    面试50题:

    题目:第一个只出现一次的字符

    题:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。

    解题思路一:利用Python特性

    # -*- coding:utf-8 -*-
    class Solution:
        def FirstNotRepeatingChar(self, s):
            # write code here
            if not s or len(s)<=0:
                return -1
            for i in s:
                if s.count(i)==1:
                    return s.index(i)
            return -1

    解题思路二:自定义一个哈希表,键值key为字符,值value为该字符出现的次数。

    # -*- coding:utf-8 -*-
    class Solution:
        def FirstNotRepeatingChar(self, s):
            # write code here
            if len(s)<=0:
                return -1
            
            char_dict={}
            for i in s:
                if i in char_dict:
                    char_dict[i]+=1
                else:
                    char_dict[i]=1
            for index,value in enumerate(s):
                if char_dict[value]==1:
                    return index
            return -1

    题目拓展:字符流中第一个只出现一次的字符。

    题:

    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。如果当前字符流没有存在出现一次的字符,返回#字符。
     
    解题代码:
    # -*- coding:utf-8 -*-
    class Solution:
        # 返回对应char
        def __init__(self):
            # 引入两个辅助空间:alist数组存储当前读入字符流的字符(按顺序)
            # char_dict存储字符出现的次数,如果字符出现大于1次,为简单起见,统一记为2次。
            self.alist=[]
            self.char_dict={}
        def FirstAppearingOnce(self):
            # write code here
            while len(self.alist)>0 and self.char_dict[self.alist[0]]>1:
                self.alist.pop(0)
            if len(self.alist)>0:
                return self.alist[0]
            return '#'
            
        def Insert(self, char):
            # write code here
            if char not in self.char_dict.keys():
                self.char_dict[char]=1
                self.alist.append(char)
            else:
                self.char_dict[char]=2
  • 相关阅读:
    给读者、学生、初学者的话(不管你买哪一本计算机书,都适用)
    [回忆]我是怎么落进「写程序」这个大火坑的?
    CF1093E [Intersection of Permutations]
    CF712E [Memort and Casinos]
    CF1093G [Multidimensional Queries]
    FFT与一些冷门问题
    平面图转对偶图&19_03_21校内训练 [Everfeel]
    19_03_26校内训练[魔法卡片]
    洛谷 P4515 [COCI20092010#6] XOR
    NTT模板(无讲解)
  • 原文地址:https://www.cnblogs.com/yanmk/p/9230974.html
Copyright © 2011-2022 走看看