第54题——字符流中第一个不重复的字符

403 阅读1分钟

题目:

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

思路:

利用hash,新建一个hash[256]

Java

package nowcoder;

public class S54_FirstAppearOnce {
    int[] hash = new int[256];
    StringBuffer sb = new StringBuffer();
    public void insert(char ch){
        sb.append(ch);
        if (hash[ch] == 0)
            hash[ch] = 1;
        else hash[ch] += 1;
    }
    public char firstAppearOnce(){
        char[] str = sb.toString().toCharArray();
        for (char chars : str){
            if (hash[chars] == 1)
                return chars;
        }
        return '#';
    }
    public static void main(String[] args){
        S54_FirstAppearOnce s54 = new S54_FirstAppearOnce();
        String str = "google";
        char[] ch = str.toCharArray();
        for (int i=0;i<str.length();i++){
            s54.insert(ch[i]);
        }
        System.out.println(s54.firstAppearOnce());
    }
}

Python

class FirstAppearOnce:
    def __init__(self):
        self.s = ""
    def FirstAppearOnce(self):
        res = list(filter(lambda c: self.s.count(c) == 1, self.s))
        return res[0] if res else "#"
    def Insert(self, char):
        self.s += char
if __name__ == '__main__':
    test = FirstAppearOnce()
    chars = ['g','o','o','g','l','e']
    for i in chars:
        test.Insert(i)
    print(test.FirstAppearOnce())