Posted onInLeetcodeViews: Valine: Symbols count in article: 8.1kReading time ≈7 mins.
Introduce to Trie
What is Trie
A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string (a prefix). Each node might have several children nodes while the paths to different children nodes represent different characters. And the strings the child nodes represent will be the origin string represented by the node itself plus the character on the path.
How to represent
Dict
In Python we can use Dictionary to represent it, key is the char and value is the dict. It can save some space but slower because we need to calculate the hashcode every time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classTrie(object): def__init__(self): """ Initialize your data structure here. """ self.root = dict() definsert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ curr = self.root for char in word: if char notin curr: curr[char] = dict() curr = curr[char] curr['#'] = '#'
from collections import defaultdict classTrieNode(object): def__init__(self): """ Initialize your data structure here. """ self.nodes = defaultdict(TrieNode) # Easy to insert new node. self.isword = False# True for the end of the trie. classTrie(object):
def__init__(self): """ Initialize your data structure here. """ self.root = TrieNode() definsert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ curr = self.root for char in word: curr = curr.nodes[char] curr.isword = True
defget(self, key): """ :type key: int :rtype: int """ if key in self.dic: n = self.dic[key] self._remove(n) self._add(n) return n.val return-1
defput(self, key, value): """ :type key: int :type value: int :rtype: void """ if key in self.dic: self._remove(self.dic[key]) n = Node(key, value) self._add(n) # imp value - node self.dic[key] = n if len(self.dic) > self.capacity: n = self.head.next self._remove(n) del(self.dic[n.key]) def_add(self, node): p = self.tail.prev p.next = node self.tail.prev = node node.prev = p node.next = self.tail def_remove(self, node): p = node.prev n = node.next p.next = n n.prev = p
# Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
Posted onEdited onViews: Valine: Symbols count in article: 357Reading time ≈1 mins.
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
classSolution(object): defminSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ # sliding widows ifnot nums: return0 l, r = 0, 0 minLength = len(nums)+1 res = 0 while r < len(nums): res += nums[r] r += 1 while res >= s: minLength = min(minLength, r - l) res -= nums[l] l += 1 return0if minLength == len(nums)+1else minLength
713. Subarray Product Less Than K
这道题甚至是上一道题的简略版本,要求出所有符合条件的。
1 2 3 4 5 6 7 8 9 10 11 12
classSolution(object): defnumSubarrayProductLessThanK(self, nums, k): if k <= 1: return0 prod = 1 ans = left = 0 for right, val in enumerate(nums): prod *= val while prod >= k: prod /= nums[left] left += 1 ans += right - left + 1 return ans
763. Partition Labels
简化版本的windows题
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defpartitionLabels(self, S): last = {c: i for i, c in enumerate(S)} j = anchor = 0 ans = [] for i, c in enumerate(S): # update j like a sliding window j = max(j, last[c]) if i == j: ans.append(i - anchor + 1) anchor = i + 1 return ans
from collections import defaultdict classSolution(object): defminWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ ifnot s: return"" ifnot t: return"" useddict = defaultdict(int) for char in t: useddict[char] += 1 length = len(t) minnum,start,end = len(s)+1,0,0 head = 0 for i in range(len(s)): if s[i] in useddict: useddict[s[i]] -= 1 if useddict[s[i]]>=0: length -= 1 while length==0: if i - start+1 < minnum: minnum = i-start+1 head = start if s[start] in useddict: useddict[s[start]] += 1 if useddict[s[start]] > 0: ## more same char was used length += 1 start += 1 return s[head:head+minnum] if minnum <= len(s) else""