边工作边刷题:70天一遍leetcode: day 95
Reverse Vowels of a String
要点:记题,这题的是对换前后对应的Vowel字符。注意python string是immutable的,所以必然要额外O(n) space。2-line code的基本思路:
- 一行反向generate vowel,另一行根据这个顺序从正向匹配单个vowel来取代(reverse不用双指针一样,就是scan两遍)
- 用generator逐个产生翻转string的vowel。然后用re.sub(pattern, repl, string, count=0, flags=0)来从左到右替换。
细节:
- (for)是产生generator,要用reversed,s.reverse()是不存在的,str是immutable,就算存在,也是in-place reverse,不返回
- re的pattern: (?i)[aeiou] (?i)表示case-insensitive,pattern别忘了’ ’,repl可以是list,所以可以是generator (lambda只是对list做变换),用next()得到下一个元素
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.ws = size
self.sumval = 0
self.window = deque()
def next(self, val):
"""
:type val: int
:rtype: float
"""
if len(self.window)==self.ws:
self.sumval-=self.window.popleft()
self.sumval+=val
self.window.append(val)
return self.sumval/len(self.window)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)