1. 程式人生 > >劍指offer 面試50題

劍指offer 面試50題

app -c off esc 數組 ring GC pen 如果

面試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

劍指offer 面試50題