classSolution { public: boolisValid(string s){ stack<char> q; for (char c : s) { if (c == '[' || c == '{' || c == '(') q.push(c); else { if (q.empty()) returnfalse; char top = q.top(); q.pop(); if (c == ')' && top != '(' || c == '}' && top != '{' || c == ']' && top != '[') returnfalse; } } return q.empty(); } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defisValid(self, s): """ :type s: str :rtype: bool """ q = [] for c in s: if c in ['(','{','[']: q.append(c) else: ifnot q: returnFalse top = q.pop() if c == ')'and top != '('or c == '}'and top != '{'or c == ']'and top != '[': returnFalse returnnot q
146. LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
classSolution: # @param tokens, a list of string # @return an integer defevalRPN(self, tokens): stack = [] for i in tokens: try: temp = int(i) stack.append(temp) except Exception, e: b,a=stack[-1],stack[-2] stack.pop() stack.pop() if i == '+': a = a+b elif i=='-': a = a-b elif i=='*': a = a*b elif i=='/': a = int(a*1.0/b) stack.append(a) return stack[-1]
155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
classMinStack { std::stack<int> s; std::stack<int> min_s; public: /** initialize your data structure here. */ MinStack() {} voidpush(int x){ s.push(x); if (min_s.empty() || min_s.top() >= x) { min_s.push(x); } } voidpop(){ int x = s.top(); s.pop(); if (x == min_s.top()) { min_s.pop(); } } inttop(){ return s.top(); } intmin(){ return min_s.top(); } };
187. Repeated DNA Sequences
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
classSolution: # @param s, a string # @return a list of strings deffindRepeatedDnaSequences(self, s): dic ,ans, n=set(),set(),len(s) for i in xrange(n-9): cur = s[i:i+10] if cur in dic: ans.add(cur) else: dic.add(cur) returnlist(ans)
208. Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Note: You may assume that all inputs are consist of lowercase letters a-z.
// Inserts a word into the trie. voidinsert(string word){ TrieNode *p = root; for (int i = 0; i < word.length(); i++){ int id = index(word[i]); if (!p->child[id]){ TrieNode *t = newTrieNode(); p->child[id] = t; } p = p->child[id]; } p->end = true; }
// Returns if the word is in the trie. boolsearch(string word){ TrieNode *p = match_word(word); return p && p->end; }
// Returns if there is any word in the trie // that starts with the given prefix. boolstartsWith(string prefix){ returnmatch_word(prefix); }
~Trie() { deleteNode(root); }
voiddeleteNode(TrieNode *root){ if (!root) return; for (int i = 0; i < TrieNode::c_size; i++){ deleteNode(root->child[i]); } delete root; }
private: TrieNode* root;
TrieNode* match_word(const string &word){ TrieNode *p = root; for (int i = 0; i < word.length(); i++){ int id = index(word[i]); if (!p->child[id]) returnNULL; p = p->child[id]; } return p; } };
211. Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
1 2 3
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
// Adds a word into the data structure. voidaddWord(string word){ TrieNode *p = root; for (int i = 0; i < word.length(); i++){ int id = index(word[i]); if (!p->child[id]){ TrieNode *t = newTrieNode(); p->child[id] = t; } p = p->child[id]; } p->end = true; }
// Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. boolsearch(string word){ returnmatch_word(root,0,word); }
~WordDictionary() { deleteNode(root); }
voiddeleteNode(TrieNode *root){ if (!root) return; for (int i = 0; i < TrieNode::c_size; i++){ deleteNode(root->child[i]); } delete root; }
private: TrieNode* root; boolmatch_word(TrieNode *p ,int k,const string &word){ if (!p || k > word.length()) returnfalse; if (k == word.length() && p->end) returntrue; for (; k < word.length(); k++){ if (word[k] == '.') { for (int j = 0; j < TrieNode::c_size; j++){ if (match_word(p->child[j], k + 1, word)) returntrue; } returnfalse; } else{ int id = index(word[k]); if (!p->child[id]) returnfalse; p = p->child[id]; } } return p->end; } };
212. Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example, Given words = ["oath","pea","eat","rain"] and board =
// Inserts a word into the trie. voidinsert(string word){ TrieNode *p = root; for (int i = 0; i < word.length(); i++){ int id = index(word[i]); if (!p->child[id]){ TrieNode *t = newTrieNode(); p->child[id] = t; } p = p->child[id]; } p->end = true; }
~Trie() { deleteNode(root); }
voiddeleteNode(TrieNode *root){ if (!root) return; for (int i = 0; i < TrieNode::c_size; i++){ deleteNode(root->child[i]); } delete root; }
};
constint dx[4] = { 1, -1, 0, 0 }; constint dy[4] = { 0, 0, 1, -1 }; classSolution { public: unordered_set<string> ans; vector<string> findWords(vector<vector<char>>& board, vector<string>& words){ vector<vector<bool> > vis(board.size(), vector<bool>(board[0].size(), 0)); Trie wordTrie; for (int i = 0; i < words.size(); i++) wordTrie.insert(words[i]); for (int i = 0; i < board.size(); i++){ for (int j = 0; j < board[0].size(); j++){ if (wordTrie.getRoot()->child[board[i][j] - 'a']){ vis[i][j] = true; string cur; cur.push_back(board[i][j]); dfs(i, j, cur, board, vis, wordTrie.getRoot()->child[board[i][j] - 'a']); vis[i][j] = false; } } } vector<string> res; for (auto it = ans.begin(); it != ans.end(); it++){ res.push_back(*it); } return res; }
voiddfs(int x, int y, string cur, vector<vector<char> >& board, vector<vector<bool> >&vis, TrieNode* p){ if (p->end) ans.insert(cur); for (int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; if (ok(nx, ny, board.size(), board[0].size()) && !vis[nx][ny] && p->child[board[nx][ny] - 'a']){ vis[nx][ny] = true; dfs(nx, ny, cur + board[nx][ny], board, vis, p->child[board[nx][ny] - 'a']); vis[nx][ny] = false; } } }
inlineboolok(int nx, int ny, int m, int n){ if (nx < 0 || nx >= m || ny < 0 || ny >= n) returnfalse; returntrue; } };
218. The Skyline Problem
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you aregiven the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).
Buildings
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
Notes:
The number of buildings in any input list is guaranteed to be in the range [0, 10000].
The input list is already sorted in ascending order by the left x position Li.
The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
classSolution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int,int>> heigtht; for (int i = 0; i < buildings.size(); i++) { heigtht.push_back(make_pair(buildings[i][0], -buildings[i][2])); heigtht.push_back(make_pair(buildings[i][1], buildings[i][2])); } sort(heigtht.begin(), heigtht.end(), cmp); vector<pair<int, int>> ans; unordered_map<int, int> m; priority_queue<int> q; int pre = 0; q.push(pre); for (int i = 0; i < heigtht.size(); i++) { if (heigtht[i].second < 0) { q.push(-heigtht[i].second); } else { ++m[heigtht[i].second]; while (!q.empty() && m[q.top()] > 0) { --m[q.top()]; q.pop(); } } int cur = q.top(); if (cur != pre) { pre = cur; ans.push_back(make_pair(heigtht[i].first,cur)); } } return ans; } };
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the _k_numbers in the window. Each time the sliding window moves right by one position.
For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
classSolution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k){ if (nums.empty()) return {}; deque<int> q; for (int i = 0; i < k; ++i) { while (!q.empty() && nums[i] > nums[q.back()]) { q.pop_back(); } q.emplace_back(i); } vector<int> ans = {nums[q.front()]}; for (int i = k; i < nums.size(); ++i) { if (q.front() + k <= i) { q.pop_front(); } while (!q.empty() && nums[i] > nums[q.back()]) { q.pop_back(); } q.emplace_back(i); ans.emplace_back(nums[q.front()]); } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defmaxSlidingWindow(self, nums: List[int], k: int) -> List[int]: ifnot nums: return [] if k == 1: return nums ans = [] q = deque() for i inrange(len(nums)): if q and q[0] <= i - k: q.popleft() while q and nums[q[-1]] <= nums[i]: q.pop() q.append(i) if i >= k - 1: ans.append(nums[q[0]]) return ans
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger]
classNestedIterator(object): def__init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ defsolve(nestedList): res = [] for x in nestedList: if x.isInteger(): res.append(x.getInteger()) else: res.extend(solve(x.getList())) return res
self.ans = solve(nestedList)[::-1]
defnext(self): """ :rtype: int """ return self.ans.pop()
public List<Interval> getIntervals() { returnnewArrayList<>(map.values()); } }
432. All O'one Data Structure
Implement a data structure supporting the following operations:
Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".
Challenge: Perform all these in O(1) time complexity.
voidremoveNodeKey(string key,list<LinkListNode>::iterator node){ node->keys.erase(key); if (!node->keys.size()) linklist.erase(node); }
public: /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ voidinc(string key){ auto it = keyToNode.find(key); int val = 0; if (it != keyToNode.end()) { auto next = it->second, node = next++; if (next == linklist.end() || next->val != node->val + 1) next = linklist.insert(next, { node->val + 1,{ key } }); else next->keys.insert(key); removeNodeKey(key, node); keyToNode[key] = next; } else { auto node = linklist.begin() != linklist.end() && linklist.begin()->val == 1 ? linklist.begin() : linklist.end(); if (node == linklist.end()) node = linklist.insert(linklist.begin(), { 1,{ key } }); else linklist.begin()->keys.insert(key); keyToNode[key] = node; } }
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ voiddec(string key){ auto it = keyToNode.find(key); if (it == keyToNode.end()) return; auto pre = it->second, node = pre != linklist.begin() ? pre-- : pre; if (node->val == 1) { keyToNode.erase(key); removeNodeKey(key, node); } else { if (node == linklist.begin() || pre->val != node->val - 1) pre = linklist.insert(node, { node->val - 1,{ key } }); else pre->keys.insert(key); keyToNode[key] = pre; removeNodeKey(key, node); } }
/** Returns one of the keys with maximal value. */ string getMaxKey(){ return linklist.empty() ? "" : *(linklist.rbegin()->keys.begin()); }
/** Returns one of the keys with Minimal value. */ string getMinKey(){ return linklist.empty() ? "" : *(linklist.begin()->keys.begin()); } };
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ voidinc(string key){ auto it = keyToNode.find(key); int val = 0; LinkListNode * node = NULL; if (it != keyToNode.end()) { node = it->second; val = node->val; node = linklist->removeKey(key, node, false); } keyToNode[key] = linklist->inc(key, val, node); }
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ voiddec(string key){ auto it = keyToNode.find(key); if (it == keyToNode.end()) return; LinkListNode * node = it->second; int val = node->val; node = linklist->removeKey(key, node, true); if (val == 1) { keyToNode.erase(key); } else { keyToNode[key] = linklist->dec(key, val, node); } }
/** Returns one of the keys with maximal value. */ string getMaxKey(){ return linklist->getMaxKey(); }
/** Returns one of the keys with Minimal value. */ string getMinKey(){ return linklist->getMinKey(); } };
/** * Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ publicvoidinc(String key) { LinkListNodenode= keyToNode.getOrDefault(key, null); intval=0; if (node != null) { val = node.val; node = linklist.removeKey(key, node, false); } keyToNode.put(key, linklist.inc(key, val, node)); }
/** * Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ publicvoiddec(String key) { LinkListNodenode= keyToNode.getOrDefault(key, null); if (node == null) return; intval= node.val; node = linklist.removeKey(key, node, true); if (val == 1) { keyToNode.remove(key); } else { keyToNode.put(key, linklist.dec(key, val, node)); } }
/** * Returns one of the keys with maximal value. */ public String getMaxKey() { return linklist.getMaxKey(); }
/** * Returns one of the keys with Minimal value. */ public String getMinKey() { return linklist.getMinKey(); } }
definc(self, key): """ Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void """ node = self.key_to_node.get(key, None) if node: # exists val = node.val node = self.linklist.remove_key(node, key) else: val = 0 self.key_to_node[key] = self.linklist.inc_key(key, val, node)
defdec(self, key): """ Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. :type key: str :rtype: void """ node = self.key_to_node.get(key, None) ifnot node: return val = node.val node = self.linklist.remove_key(node, key,is_dec=True) if val == 1: del self.key_to_node[key] else: self.key_to_node[key] = self.linklist.dec_key(key, val, node)
defgetMaxKey(self): """ Returns one of the keys with maximal value. :rtype: str """ return self.linklist.get_max_key()
defgetMinKey(self): """ Returns one of the keys with Minimal value. :rtype: str """ return self.linklist.get_min_key()