-
Notifications
You must be signed in to change notification settings - Fork 7
/
appear_once.py
78 lines (63 loc) · 1.91 KB
/
appear_once.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
# author: Xiguang Liu<[email protected]>
# 2018-05-04 16:34
# 题目描述:https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
class Solution:
def __init__(self):
self.stack = Node(None)
self.appear = set()
self.removed = set()
# 返回对应char
def FirstAppearingOnce(self):
return '#' if self.stack.next is None else self.stack.next.val
def Insert(self, char):
if char not in self.appear:
self.appear.add(char)
self.stack.push(char)
else:
if char not in self.removed:
self.removed.add(char)
self.stack.remove(char)
def reset(self):
self.stack = Node(None)
self.appear = set()
class Node:
def __init__(self, x):
self.val = x
self.next = None
def push(self, x):
p = self
while p.next:
p = p.next
p.next = Node(x)
def remove(self, x):
p = self
while p.next.val != x:
p = p.next
p.next = p.next.next
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
self.s = Solution()
def test_1(self):
self.s.reset()
self.s.Insert('g')
self.s.Insert('o')
self.s.Insert('o')
self.s.Insert('g')
self.s.Insert('l')
self.s.Insert('e')
self.assertEqual('l', self.s.FirstAppearingOnce())
def test_2(self):
self.s.reset()
self.s.Insert('h')
self.s.Insert('e')
self.s.Insert('l')
self.s.Insert('l')
self.s.Insert('o')
self.s.Insert('w')
self.s.Insert('o')
self.s.Insert('r')
self.s.Insert('l')
self.s.Insert('d')
self.assertEqual('h', self.s.FirstAppearingOnce())