diff --git a/best-time-to-buy-and-sell-stock/printjin-gmailcom.py b/best-time-to-buy-and-sell-stock/printjin-gmailcom.py new file mode 100644 index 000000000..fa225ef62 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/printjin-gmailcom.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, price): + min_price = float('inf') + max_profit = 0 + for price in prices: + if price < min_price: + min_price = price + elif price - min_price > max_profit: + max_profit = price - min_price + return max_profit diff --git a/encode-and-decode-strings/printjin-gmailcom.py b/encode-and-decode-strings/printjin-gmailcom.py new file mode 100644 index 000000000..06957083a --- /dev/null +++ b/encode-and-decode-strings/printjin-gmailcom.py @@ -0,0 +1,18 @@ +class Solution: + def encode(self, strs): + res = '' + for s in strs: + res += str(len(s)) + '#' + s + return res + + def decode(self, s): + res = [] + i = 0 + while i < len(s): + j = i + while s[j] != '#': + j += 1 + length = int(s[i:j]) + res.append(s[j+1:j+1+length]) + i = j + 1 + length + return res diff --git a/group-anagrams/printjin-gmailcom.py b/group-anagrams/printjin-gmailcom.py new file mode 100644 index 000000000..ffcc1c2f8 --- /dev/null +++ b/group-anagrams/printjin-gmailcom.py @@ -0,0 +1,11 @@ +from collections import defaultdict + +class Solution: + def groupAnagrams(self, strs): + anagrams = defaultdict(list) + for word in strs: + count = [0] * 26 + for c in word: + count[ord(c) - ord('a')] += 1 + anagrams[tuple(count)].append(word) + return list(anagrams.values()) diff --git a/implement-trie-prefix-tree/printjin-gmailcom.py b/implement-trie-prefix-tree/printjin-gmailcom.py new file mode 100644 index 000000000..a135f04ac --- /dev/null +++ b/implement-trie-prefix-tree/printjin-gmailcom.py @@ -0,0 +1,27 @@ +class Trie: + def __init__(self): + self.trie = {} + + def insert(self, word): + node = self.trie + for char in word: + if char not in node: + node[char] = {} + node = node[char] + node['#'] = {} + + def search(self, word): + node = self.trie + for char in word: + if char not in node: + return False + node = node[char] + return '#' in node + + def startsWith(self, prefix): + node = self.trie + for char in prefix: + if char not in node: + return False + node = node[char] + return True diff --git a/word-break/printjin-gmailcom.py b/word-break/printjin-gmailcom.py new file mode 100644 index 000000000..b882e0a09 --- /dev/null +++ b/word-break/printjin-gmailcom.py @@ -0,0 +1,20 @@ +class Solution: + def wordBreak(self, s, wordDict): + wordSet = set(wordDict) + memo = {} + + def backtrack(start): + if start == len(s): + return True + if start in memo: + return memo[start] + + for end in range(start + 1, len(s) + 1): + if s[start:end] in wordSet and backtrack(end): + memo[start] = True + return True + + memo[start] = False + return False + + return backtrack(0)