├── Array ├── Easy │ └── 1.Two Sum.md └── Medium │ └── 11.Container With Most Water.md ├── Hash Table └── Easy │ └── 290.Word Pattern.md ├── Help └── complexitypython.txt ├── Linked List ├── Easy │ ├── 141.Linked List Cycle │ │ ├── Linked List Cycle.c │ │ ├── Linked List Cycle.cpp │ │ └── Linked List Cycle.py │ ├── 160.Intersection of Two Linked Lists │ │ ├── Intersection of Two Linked Lists.c │ │ ├── Intersection of Two Linked Lists.cpp │ │ └── Intersection of Two Linked Lists.py │ ├── 203.Remove Linked List Elements │ │ ├── Remove Linked List Elements.c │ │ └── Remove Linked List Elements.cpp │ ├── 206.Reverse Linked List │ │ ├── Reverse Linked List-iteratively.c │ │ ├── Reverse Linked List-recursively.c │ │ └── Reverse Linked List.py │ ├── 21.Merge Two Sorted Lists │ │ ├── Merge Two Sorted Lists.c │ │ ├── Merge Two Sorted Lists.cpp │ │ └── Merge Two Sorted Lists.py │ ├── 234.Palindrome Linked List │ │ ├── Palindrome Linked List.c │ │ ├── Palindrome Linked List.cpp │ │ └── Palindrome.py │ ├── 237.Delete Node in a Linked List │ │ ├── Delete Node in a Linked List.c │ │ └── Delete Node in a Linked List.py │ └── 83.Remove Duplicates from Sorted List │ │ ├── Remove Duplicates from Sorted List.c │ │ ├── Remove Duplicates from Sorted List.cpp │ │ └── Remove Duplicates from Sorted List.py └── Medium │ ├── 1367.Linked List in Binary Tree │ ├── 2.Add Two Numbers.md │ └── 61.Rotate List │ ├── Rotate List.c │ ├── Rotate List.cpp │ └── Rotate List.py ├── README.md ├── Stack ├── Easy │ ├── 155.Min Stack │ │ └── Min Stack.cpp │ ├── 20.Valid Parentheses │ │ └── Valid Parentheses.cpp │ ├── 225.Implement Stack using Queues │ │ └── Implement Stack using Queues.cpp │ ├── 232.Implement Queue using Stacks │ │ └── Implement Queue using Stacks.cpp │ └── 496.Next Greater Element I │ │ └── Next Greater Element I.cpp └── Medium │ └── 150.Evaluate Reverse Polish Notation │ └── Evaluate Reverse Polish Notation.cpp ├── String ├── Easy │ ├── 125.Valid Palindrome.md │ ├── 13.Roman to Integer │ │ ├── README.md │ │ └── Roman to Integer.py │ ├── 14.Longest Common Prefix │ │ ├── Longest Common Prefix.py │ │ └── README.md │ ├── 28.Implement strStr.md │ ├── 344.Reverse String │ │ ├── Reverse String.cpp │ │ └── Reverse String.py │ ├── 345.Reverse Vowels of a String.md │ ├── 38.Count and Say │ │ ├── Count and Say.py │ │ └── README.md │ ├── 383.Ransom Note.md │ ├── 434.Number of Segments in a String │ │ ├── Number of Segments in a String.cpp │ │ └── Number of Segments in a String.py │ ├── 520.Detect Capital │ │ ├── Detect Capital.cpp │ │ └── Detect Capital.py │ ├── 521.Longest Uncommon Subsequence I │ │ └── Longest Uncommon Subsequence I.py │ ├── 541.Reverse String II │ │ ├── Reverse String II.cpp │ │ └── Reverse String II.py │ ├── 551. Student Attendance Record I │ │ └── Student Attendance Record I.py │ ├── 557.Reverse Words in a String III │ │ ├── Reverse Words in a String III.cpp │ │ └── Reverse Words in a String III.py │ ├── 657.Judge Route Circle │ │ └── Judge Route Circle.py │ └── 67.Add Binary │ │ ├── 67.Add Binary.cpp │ │ └── Add Binary.py └── Medium │ ├── 17.Letter Combinations of a Phone Number.md │ ├── 22.Generate Parentheses.md │ ├── 3.Longest Substring Without Repeating Characters.md │ ├── 43.Multiply Strings.md │ ├── 5.Longest Palindromic Substring.md │ └── 609.Find Duplicate File in System.md └── Tree ├── Easy ├── 111.Minimum Depth of Binary Tree │ ├── Minimum Depth of Binary Tree-1.py │ ├── Minimum Depth of Binary Tree-2.py │ └── Minimum Depth of Binary Tree.cpp ├── 112.Path Sum │ ├── Path Sum-1.py │ ├── Path Sum-2.py │ └── Path Sum.cpp ├── 235.Lowest Common Ancestor of a Binary Search Tree │ ├── Lowest Common Ancestor of a Binary Search Tree-1.py │ ├── Lowest Common Ancestor of a Binary Search Tree-2.py │ └── Lowest Common Ancestor of a Binary Search Tree.cpp ├── 501.Find Mode in Binary Search Tree │ ├── Find Mode in Binary Search Tree.cpp │ └── Find Mode in Binary Search Tree.py ├── 543.Diameter of Binary Tree │ ├── Diameter of Binary Tree.cpp │ └── Diameter of Binary Tree.py └── 606.Construct String from Binary Tree │ ├── Construct String from Binary Tree.cpp │ └── Construct String from Binary Tree.py └── Medium └── 113.Path Sum II └── Path Sum II.py /Array/Easy/1.Two Sum.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定一个整数的数组nums,返回相加为target的两个数字的索引值。 4 | 5 | 假设每次输入都只有一个答案,并且不会使用同一个元素两次。 6 | 7 | **举例:** 8 | 9 | ``` stylus 10 | Given nums = [2, 7, 11, 15], target = 9, 11 | 12 | Because nums[0] + nums[1] = 2 + 7 = 9, 13 | return [0, 1]. 14 | ``` 15 | 16 | # 思路 17 | 18 | 最初,我的解题思路是最简单的遍历,如果数组nums的元素a小于target,那么就在数组中寻找另外一个b,使a+b=target。 19 | 20 | ``` python 21 | class Solution(object): 22 | def twoSum(self, nums, target): 23 | """ 24 | :type nums: List[int] 25 | :type target: int 26 | :rtype: List[int] 27 | """ 28 | result = [] 29 | for i, each in enumerate(nums): 30 | if abs(target-each) >=0 and i not in result: 31 | try: 32 | tmp = nums.index(target - each) 33 | if tmp != i: 34 | result.append(i) 35 | result.append(tmp) 36 | except: 37 | continue 38 | return result 39 | ``` 40 | 41 | 运行通过,但是运行速度特别慢!Beats才20%+。list的index操作时间复杂度为O(1),list的append操作时间复杂度也为O(1)。list的not in时间复杂度为O(n),在算上循环,总共时间复杂度为O(n^2)?所以才这么慢吧.... 42 | 43 | 继续想一些更高级的解决办法。 44 | 45 | 使用哈希表,也就是散列表,在Python就是字典。使用方法很巧妙,直接看代码吧! 46 | 47 | ``` python 48 | class Solution(object): 49 | def twoSum(self, nums, target): 50 | """ 51 | :type nums: List[int] 52 | :type target: int 53 | :rtype: List[int] 54 | """ 55 | if len(nums) <= 1: 56 | return False 57 | buff_dict = {} 58 | for i in range(len(nums)): 59 | if nums[i] in buff_dict: 60 | return [buff_dict[nums[i]], i] 61 | else: 62 | buff_dict[target - nums[i]] = i 63 | ``` 64 | 65 | Beats 90%+。 66 | 67 | 68 | -------------------------------------------------------------------------------- /Array/Medium/11.Container With Most Water.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 求最大水容器,给定一个包含正整数的数组,a1,a2,...,an。每个元素都可以呈现成一个点(i,ai)。过每个点,做垂直于x轴的垂线,得到对应交点(0,ai)。(0,ai)和(i,ai)构成一条之前。每条直线两两组合,构成一个储水容器,找到存储量最大的那个容器。 4 | 5 | **举例:** 6 | 7 | ``` stylus 8 | Input:[1,3,5] 9 | (0,1) -> (1,1) 10 | (0,3) -> (2,3) 11 | (0,5) -> (3,5) 12 | Output:3 13 | ``` 14 | 15 | 输入是[1,3,5],那么一共有三条垂直与x轴的直线,直线两两组合,面积最大为3。 16 | 17 | # 思路 18 | 19 | 最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到左边大于右边为止就行了 20 | 21 | # 代码 22 | 23 | **Python:** 24 | 25 | ``` python 26 | class Solution(object): 27 | def maxArea(self, height): 28 | """ 29 | :type height: List[int] 30 | :rtype: int 31 | """ 32 | area_tmp = 0 33 | area_max = 0 34 | left = 0 35 | right = len(height) - 1 36 | while(left < right): 37 | min_height = min(height[left], height[right]) 38 | area_tmp = (right - left) * min_height 39 | if area_tmp > area_max: 40 | area_max = area_tmp 41 | if height[left] < height[right]: 42 | left += 1 43 | else: 44 | right -= 1 45 | return area_max 46 | ``` 47 | 48 | **C++:** 49 | 50 | ``` cpp 51 | class Solution { 52 | public: 53 | int maxArea(vector& height) { 54 | int left = 0; 55 | int right = height.size() - 1; 56 | int area_tmp = 0; 57 | int area_max = 0; 58 | while (left < right) { 59 | area_tmp = (right - left) * (height[left] < height[right] ? height[left] : height[right]); 60 | if (area_tmp > area_max) { 61 | area_max = area_tmp; 62 | } 63 | if (height[left] < height[right]) { 64 | left++; 65 | } 66 | else { 67 | right--; 68 | } 69 | } 70 | return area_max; 71 | } 72 | }; 73 | ``` 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Hash Table/Easy/290.Word Pattern.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 根据pattern和str,找到是否符合这个pattern匹配模式。 4 | 5 | **举例:** 6 | 7 | * pattern = "abba", str = "dog cat cat dog" should return true. 8 | * pattern = "abba", str = "dog cat cat fish" should return false. 9 | * pattern = "aaaa", str = "dog cat cat dog" should return false. 10 | * pattern = "abba", str = "dog dog dog dog" should return false. 11 | 12 | **注意:** 13 | 14 | 假设pattern只包含小写字母,而str包含由空格分隔的小写字母。 15 | 16 | # 思路 17 | 18 | 对于python,巧妙使用map和find函数即可。 19 | 20 | # 代码 21 | 22 | **python:** 23 | 24 | ``` python 25 | class Solution: 26 | def wordPattern(self, pattern, str): 27 | """ 28 | :type pattern: str 29 | :type str: str 30 | :rtype: bool 31 | """ 32 | t = str.split(' ') 33 | return list(map(pattern.find, pattern)) == list(map(t.index, t)) 34 | ``` 35 | 36 | 37 | -------------------------------------------------------------------------------- /Help/complexitypython.txt: -------------------------------------------------------------------------------- 1 | Complexity of Python Operations 2 | 3 | 4 | In this lecture we will learn the complexity classes of various operations on 5 | Python data types. Then we wil learn how to combine these complexity classes to 6 | compute the complexity class of all the code in a function, and therefore the 7 | complexity class of the function. This is called "static" analysis, because we 8 | do not need to run any code to perform it (contrasted with Dynamic or Emperical 9 | Analysis, when we do run code and take measurements). 10 | 11 | ------------------------------------------------------------------------------ 12 | 13 | Python Complexity Classes 14 | 15 | In ICS-46 we will write low-level implementations of all of Python's data types 16 | and see/understand WHY these complexity classes apply. For now we just need to 17 | try to absorb (not memorize) this information, with some -but minimal- 18 | justification. 19 | 20 | Binding a value to any name (copying a refernce) is O(1). Simple operators on 21 | integers (whose values are small: e.g., under 12 digits) like + or == are also 22 | O(1). Assume small integers unless explicitly told otherwise. 23 | 24 | In all these examples, N = len(data-type). The operations are organized by 25 | increasing complexity 26 | 27 | Lists: 28 | Complexity 29 | Operation | Example | Class | Notes 30 | --------------+--------------+---------------+------------------------------- 31 | Index | l[i] | O(1) | 32 | Store | l[i] = 0 | O(1) | 33 | Length | len(l) | O(1) | 34 | Append | l.append(5) | O(1) | 35 | Pop | l.pop() | O(1) | same as l.pop(-1), popping at end 36 | Clear | l.clear() | O(1) | similar to l = [] 37 | 38 | Slice | l[a:b] | O(b-a) | l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N) 39 | Extend | l.extend(...)| O(len(...)) | depends only on len of extension 40 | Construction | list(...) | O(len(...)) | depends on length of ... iterable 41 | 42 | check ==, != | l1 == l2 | O(N) | 43 | Insert | l[a:b] = ... | O(N) | 44 | Delete | del l[i] | O(N) | 45 | Containment | x in/not in l| O(N) | searches list 46 | Copy | l.copy() | O(N) | Same as l[:] which is O(N) 47 | Remove | l.remove(...)| O(N) | 48 | Pop | l.pop(i) | O(N) | O(N-i): l.pop(0):O(N) (see above) 49 | Extreme value | min(l)/max(l)| O(N) | searches list 50 | Reverse | l.reverse() | O(N) | 51 | Iteration | for v in l: | O(N) | 52 | 53 | Sort | l.sort() | O(N Log N) | key/reverse mostly doesn't change 54 | Multiply | k*l | O(k N) | 5*l is O(N): len(l)*l is O(N**2) 55 | 56 | Tuples support all operations that do not mutate the data structure (and with 57 | the same complexity classes). 58 | 59 | 60 | Sets: 61 | Complexity 62 | Operation | Example | Class | Notes 63 | --------------+--------------+---------------+------------------------------- 64 | Length | len(s) | O(1) | 65 | Add | s.add(5) | O(1) | 66 | Containment | x in/not in s| O(1) | compare to list/tuple - O(N) 67 | Remove | s.remove(..) | O(1) | compare to list/tuple - O(N) 68 | Discard | s.discard(..)| O(1) | 69 | Pop | s.pop() | O(1) | 70 | Clear | s.clear() | O(1) | similar to s = set() 71 | 72 | Construction | set(...) | O(len(...)) | depends on length of ... iterable 73 | check ==, != | s != t | O(len(s)) | same as len(t): False in O(1) if 74 | the lengths are different 75 | <=/< | s <= t | O(len(s)) | issubset 76 | >=/> | s >= t | O(len(t)) | issuperset s <= t == t >= s 77 | Union | s | t | O(len(s)+len(t)) 78 | Intersection | s & t | O(len(s)+len(t)) 79 | Difference | s - t | O(len(s)+len(t)) 80 | Symmetric Diff| s ^ t | O(len(s)+len(t)) 81 | 82 | Iteration | for v in s: | O(N) | 83 | Copy | s.copy() | O(N) | 84 | 85 | Sets have many more operations that are O(1) compared with lists and tuples. 86 | Not needing to keep values in a specific order in a set (which lists/tuples 87 | require) allows for faster set operations. 88 | 89 | Frozen sets support all operations that do not mutate the data structure (and 90 | with the same complexity classes). 91 | 92 | 93 | Dictionaries: dict and defaultdict 94 | Complexity 95 | Operation | Example | Class | Notes 96 | --------------+--------------+---------------+------------------------------- 97 | Index | d[k] | O(1) | 98 | Store | d[k] = v | O(1) | 99 | Length | len(d) | O(1) | 100 | Delete | del d[k] | O(1) | 101 | get/setdefault| d.method | O(1) | 102 | Pop | d.pop(k) | O(1) | 103 | Pop item | d.popitem() | O(1) | 104 | Clear | d.clear() | O(1) | similar to s = {} or = dict() 105 | View | d.keys() | O(1) | same for d.values() 106 | 107 | Construction | dict(...) | O(len(...)) | depends # (key,value) 2-tuples 108 | 109 | Iteration | for k in d: | O(N) | all forms: keys, values, items 110 | 111 | So, most dict operations are O(1). 112 | 113 | defaultdicts support all operations that dicts support, with the same 114 | complexity classes (because it inherits all the operations); this assumes that 115 | calling the constructor when a values isn't found in the defaultdict is O(1) - 116 | which is true for int(), list(), set(), ... (the things we commonly use) 117 | 118 | Note that for i in range(...) is O(len(...)); so for i in range(1,10) is O(1). 119 | If len(alist) is N, then 120 | 121 | for i in range(len(alist)): 122 | 123 | is O(N) because it loops N times. Of course even 124 | 125 | for i in range (len(alist)//2): 126 | 127 | is O(N) because it loops N/2 times, and dropping the constant 1/2 makes 128 | it O(N): the work doubles when the list length doubles. 129 | 130 | Finally, when comparing two lists for equality, the complexity class above 131 | shows as O(N), but in reality we would need to multiply this complexity by 132 | O(==) where O(==) is the complexity class for checking whether two values in 133 | the list are ==. If they are ints, O(==) would be O(1); if they are strings, 134 | O(==) in the worst case it would be O(len(string)). This issue applies any 135 | time an == check is done. We mostly will assume == checking on values in lists 136 | is O(1): e.g., checking ints and small strings. 137 | 138 | ------------------------------------------------------------------------------ 139 | 140 | Composing Complexity Classes: Sequential and Nested Statements 141 | 142 | In this section we will learn how to combine complexity class information about 143 | simple operations into complexity information about complex operations 144 | (composed from simple operations). The goal is to be able to analyze all the 145 | statements in a functon/method to determine the complexity class of executing 146 | the function/method. 147 | 148 | ------------------------------------------------------------------------------ 149 | 150 | Law of Addition for big-O notation 151 | 152 | O(f(n)) + O(g(n)) is O( f(n) + g(n) ) 153 | 154 | That is, we when adding complexity classes we bring the two complexity classes 155 | inside the O(...). Ultimately, O( f(n) + g(n) ) results in the bigger of the two 156 | complexity class (because we drop the lower added term). So, 157 | 158 | O(N) + O(Log N) = O(N + Log N) = O(N) 159 | 160 | because N is the faster growing term. 161 | 162 | This rule helps us understand how to compute the complexity of doing any 163 | SEQUENCE of operations: executing a statement that is O(f(n)) followed by 164 | executing a statement that is O(g(n)). Executing both statements SEQUENTAILLY 165 | is O(f(n)) + O(g(n)) which is O( f(n) + g(n) ) by the rule above. 166 | 167 | For example, if some function call f(...) is O(N) and another function call 168 | g(...) is O(N Log N), then doing the sequence 169 | 170 | f(...) 171 | g(...) 172 | 173 | is O(N) + O(N Log N) = O(N + N Log N) = O(N Log N). Of course, executing the 174 | sequence (calling f twice) 175 | 176 | f(...) 177 | f(...) 178 | 179 | is O(N) + O(N) which is O(N + N) which is O(2N) which is O(N). 180 | 181 | Note that for an if statment like 182 | 183 | if test: assume complexity of test is O(T) 184 | block 1 assume complexity of block 1 is O(B1) 185 | else: 186 | block 2 assume complexity of block 2 is O(B2) 187 | 188 | The complexity class for the if is O(T) + max(O(B1),O(B2)). The test is always 189 | evaluated, and one of the blocks is always executed. In the worst case, the if 190 | will execute the block with the largest complexity. So, given 191 | 192 | if test: complexity is O(N) 193 | block 1 complexity is O(N**2) 194 | else: 195 | block 2 complexity is O(N) 196 | 197 | The complexity class for the if is O(N) + max (O(N**2),O(N))) = O(N) + O(N**2) = 198 | O(N + N**2) = O(N**2). If the test had complexity class O(N**3), then the 199 | complexity class for the if is O(N**3) + max (O(N**2),O(N))) = 200 | O(N**3) + O(N**2) = O(N**3 + N**2) = O(N**3). 201 | 202 | ------------------------------------------------------------------------------ 203 | 204 | Law of Multiplcation for big-O notation 205 | 206 | O(f(n)) * O(g(n)) is O( f(n) * g(n) ) 207 | 208 | If we repeat an O(f(N)) process O(N) times, the resulting complexity is 209 | O(N)*O(f(N)) = O( Nf(N) ). An example of this is, if some function call f(...) 210 | is O(N**2), then executing that call N times (in the following loop) 211 | 212 | for i in range(N): 213 | f(...) 214 | 215 | is O(N)*O(N**2) = O(N*N**2) = O(N**3) 216 | 217 | This rule helps us understand how to compute the complexity of doing some 218 | statement INSIDE A BLOCK controlled by a statement that is REPEATING it. We 219 | multiply the complexity class of the number of repetitions by the complexity 220 | class of the statement(s) being repeated. 221 | 222 | Compound statements can be analyzed by composing the complexity classes of 223 | their constituent statements. For sequential statements (including if tests and 224 | their block bodies) the complexity classes are added; for statements repeated 225 | in a loop the complexity classes are multiplied. 226 | 227 | Let's use the data and tools discussed above to analyze (determine their 228 | complexity classes) three different functions that each compute the same 229 | result: whether or not a list contains only unique values (no duplicates). We 230 | will assume in all three examples that len(alist) is N. 231 | 232 | 1) Algorithm 1: A list is unique if each value in the list does not occur in any 233 | later indexes: alist[i+1:] is a list containing all values after the one at 234 | index i. 235 | 236 | def is_unique1 (alist : [int]) -> bool: 237 | for i in range(len(alist)): O(N) 238 | if alist[i] in alist[i+1:]: O(N) - index+add+slice+in: O(1)+O(1)+O(N)+O(N) = O(N) 239 | return False O(1) - never executed in worst case 240 | return True O(1) 241 | 242 | The complexity class for executing the entire function is O(N) * O(N) + O(1) 243 | = O(N**2). So we know from the previous lecture that if we double the length of 244 | alist, this function takes 4 times as long to execute. 245 | 246 | Note that in the worst case, we never return False and keep executing the loop, 247 | so this O(1) does not appear in the answer. Also, in the worst case the list 248 | slice is aliset[1:] which is O(N-1) = O(N). 249 | 250 | 2) Algorithm 2: A list is unique if when we sort its values, no ADJACENT values 251 | are equal. If there were duplicate values, sorting the list would put these 252 | duplicate values right next to each other (adjacent). Here we copy the list so 253 | as to not mutate (change the order of the parameter's list) by sorting it: 254 | it turns out that copying the list does not increase the complexity class of 255 | the method. 256 | 257 | def is_unique2 (alist : [int]) -> bool: 258 | copy = list(alist) O(N) 259 | copy.sort() O(N Log N) - for fast Python sorting 260 | for i in range(len(alist)-1): O(N) - really N-1, but that is O(N); len is O(1) 261 | if copy[i] == copy[i+1]: O(1): +, 2 [i],and == ints: all O(1) 262 | return False O(1) - never executed in worst case 263 | return True O(1) 264 | 265 | The complexity class for executing the entire function is given by the sum 266 | O(N) + O(N Log N) + O(N)*O(1) + O(1) = O(N + N Log N + O(N*1) + 1) = 267 | O(N + N Log N + N + 1) = O(N Log N + 2N + 1) = O(N Log N). So the 268 | complexity class for this algorithm/function is lower than the first algorithm, 269 | the is_unique1 function. For large N unque2 will eventually run faster. Because 270 | we don't know the constants, we don't know which is faster for small N. 271 | 272 | Notice that the complexity class for sorting is dominant in this code: it does 273 | most of the work. If we double the length of alist, this function takes a bit 274 | more than twice the amount of time. In N Log N: N doubles and Log N gets a tiny 275 | bit bigger (i.e., Log 2N = 1 + Log N; e.g., Log 2000 = 1 + Log 1000 = 11, so 276 | compared to 1000 Log 1000, 2000 Log 2000 got 2.2 times bigger, or 10% bigger 277 | than just doubling). 278 | 279 | Looked at another way if T(N) = c*(N Log N), then T(2N) = c*(2N Log 2N) = 280 | c*2N Log N + c*2N = 2*T(N) + c*2N. Or, computing the doubling signature 281 | 282 | T(2N) c*2(N Log N) + c*2N 2 283 | ----- = ------------------- = 2 + ------- 284 | T(N) c*(N Log N) Log N 285 | 286 | So, the ratio is 2 + a bit (and that bit gets smaller as N increases). 287 | 288 | 3) Algorithm 3: A list is unique if when we turn it into a set, its length is 289 | unchanged: if duplicate values were added to the set, its length would be 290 | smaller than the length of the list by exactly the number of duplicates in the 291 | list added to the set. 292 | 293 | def is_unique3 (alist : [int]) -> bool: 294 | aset = set(alist) O(N): construct set from alist values 295 | return len(aset) == len(alist) O(1): 2 len (each O(1)) and == ints O(1) 296 | 297 | The complexity class for executing the entire function is O(N) + O(1) = 298 | O(N + 1) = O(N). So the complexity class for this algortihm/function is lower 299 | than both the first and second algorithms/functions. If we double the length of 300 | alist, this function takes just twice the amount of time. We could write the 301 | body of this function more simply as: return len(set(alist)) == len(alist), 302 | where evaluating set(alist) takes O(N) and then computing the two len's and 303 | comparing them for equality are all O(1). 304 | 305 | So the bottom line here is that there might be many algorithms/functions to 306 | solve some problem. If the function bodies are small, we can analyze them 307 | statically (looking at the code, not running it) to determine their complexity 308 | classes. For large problem sizes, the algorithm/function with the smallest 309 | complexity class will be best. For small problem sizes, complexity classes 310 | don't determine which is best (we need to take into account the CONSTANTS and 311 | lower order terms when problem sizes are small), but we could run the functions 312 | (dynamic analysis, aka empirical analysis) to test which is fastest on small 313 | problem sizes. 314 | 315 | ------------------------------------------------------------------------------ 316 | 317 | Using a Class (implementable 3 ways) Example: 318 | 319 | We will now look at the solution of a few problems (combining operations on a 320 | priority queue: pq) and how the complexity class of the result is affected by 321 | three different classes/implementations of priority queues. 322 | 323 | In a priority queue, we can add values and remove values to the data structure. 324 | A correctly working priority queue always removes the maximum value remaining in 325 | the priority queue (the one with the highest priority). Think of a line/queue 326 | outside of a Hollywood nightclub, such that whenever space opens up inside, the 327 | most famous person in line gets to go in (the "highest priority" person), no 328 | matter how long less famous people have been standing in line (contrast this 329 | with first come/first serve, which is a regular -non priority- queue; there, 330 | whoever is first in the line -has been standing in line longest- is admitted). 331 | 332 | For the problems below, all we need to know is the complexity class of the 333 | "add" and "remove" operations. 334 | 335 | add remove 336 | +-------------+-------------+ 337 | Implementation 1 | O(1) | O(N) | 338 | +-------------+-------------+ 339 | Implementation 2 | O(N) | O(1) | 340 | +-------------+-------------+ 341 | Implementation 3 | O(Log N) | O(Log N) | 342 | +-------------+-------------+ 343 | 344 | Implementation 1 adds the new value into the pq by appending the value at the 345 | rear of a list or the front of a linked list: both are O(1); it removes the 346 | highest priority value by scanning through the list or linked list to find the 347 | highest value, which is O(N), and then removing that value, also O(N) in the 348 | worst case (removing at the front of a list; at the rear of a linked list). 349 | 350 | Implementation 2 adds the new value into the pq by scanning the list or linked 351 | list for the right spot to put it and putting it there, which is O(N). Lists 352 | store their highest priority at the rear (linked lists at the front); it 353 | removes the highest priority value from the rear for lists (or the front for 354 | linked lists), which is O(1). 355 | 356 | Implementation 3, which is discussed in ICS-46, uses a binary heap tree (not a 357 | binary search tree) to implement both operations with "middle" complexity 358 | O(Log N): this complexity class greater than O(1) but less than O(N). Because 359 | Log N grows so slowly, O(Log N) is actually closer to O(1) than O(N) even thoug 360 | O(1) doesn't grow at all). 361 | 362 | Problem 1: Suppose we wanted to use the priority queue to sort N values: we 363 | add N values in the pq and then remove all N values (first the highest, next 364 | the second highest, ...). Here is the complexity of these combined operations 365 | for each implementation. 366 | 367 | Implementation 1: O(N)*O(1) + O(N)*O(N) = O(N) + O(N**2) = O(N**2) 368 | Implementation 2: O(N)*O(N) + O(N)*O(1) = O(N**2) + O(N) = O(N**2) 369 | Implementation 3: O(N)*O(Log N) + O(N)*O(Log N) = O(NLogN) + O(NLogN) = O(NLogN) 370 | 371 | Here, Implementation 3 has the lowest complexity class for the combined 372 | operations. Implementations 1 and 2 each do one operation quickly but the other 373 | slowly: both are done O(N) times. The slowest operation determines the 374 | complexity class, and both are equally slow. The complexity class O(Log N) is 375 | between O(1) and O(N); surprisingly, it is actually "closer" to O(1) than O(N), 376 | even though it does grow -because it grows so slowly; yes, O(1) doesn't grow at 377 | all, but O(Log N) grows very slowly: the known Universe has about 10**90 378 | particles of matter, and Log 10**90 = Log (10**3)**30 = 300, which isn't very 379 | big compared to 10**90. 380 | 381 | Problem 2: Suppose we wanted to use the priority queue to find the 10 biggest 382 | (of N) values: we would enqueue N values and then dequeue 10 values. Here is 383 | the complexity of these combined operations for each implementation.. 384 | 385 | Implementation 1: O(N)*O(1) + O(10)*O(N) = O(N) + O(N) = O(N) 386 | Implementation 2: O(N)*O(N) + O(10)*O(1) = O(N**2) + O(1) = O(N**2) 387 | Implementation 3: O(N)*O(Log N) + O(10)*O(Log N) = O(NLogN) + O(LogN) = O(NLogN) 388 | 389 | Here, Implementation 1 has the lowest complexity for the combined operations. 390 | That makes sense, as the operation done O(N) times (add) is very simple (add to 391 | the end of a list/the front of a linked list is O(1)) and the operation done a 392 | constant number of times (10, independent of N) is the expensive operation 393 | (remove, which is O(N)). It even beats the complexity of Implementation 3. So, 394 | as N gets bigger, implementation 1 will eventually become faster than the other 395 | two for the "find the 10 biggest" task. 396 | 397 | So, the bottom line here is that sometimes there is NOT a "best all the time" 398 | implementation for a data structure. We need to know what problem we are 399 | solving (the complexity classes of all the operations in various 400 | implementations and the number of times we must do these operations) to choose 401 | the most efficient implementation for solving the problem. 402 | 403 | ------------------------------------------------------------------------------ 404 | 405 | Problems: 406 | 407 | TBA 408 | -------------------------------------------------------------------------------- /Linked List/Easy/141.Linked List Cycle/Linked List Cycle.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | bool hasCycle(struct ListNode *head) { 9 | struct ListNode *fast = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 | struct ListNode *slow = (struct ListNode *)malloc(sizeof(struct ListNode)); 11 | fast = head; 12 | slow = head; 13 | while(fast != NULL && fast->next != NULL){ 14 | slow = slow->next; 15 | fast = fast->next->next; 16 | if(fast == slow){ 17 | return true; 18 | } 19 | } 20 | return false; 21 | } -------------------------------------------------------------------------------- /Linked List/Easy/141.Linked List Cycle/Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | ListNode *fast = head; 13 | ListNode *slow = head; 14 | while(fast != NULL && fast->next != NULL){ 15 | slow = slow->next; 16 | fast = fast->next->next; 17 | if(fast == slow){ 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | }; -------------------------------------------------------------------------------- /Linked List/Easy/141.Linked List Cycle/Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def hasCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: bool 12 | """ 13 | try: 14 | slow = head 15 | fast = head.next 16 | while slow is not fast: 17 | slow = slow.next 18 | fast = fast.next.next 19 | return True 20 | except: 21 | return False -------------------------------------------------------------------------------- /Linked List/Easy/160.Intersection of Two Linked Lists/Intersection of Two Linked Lists.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { 9 | struct ListNode *curA = (struct ListNode*)malloc(sizeof(struct ListNode)); 10 | struct ListNode *curB = (struct ListNode*)malloc(sizeof(struct ListNode)); 11 | curA = headA; 12 | curB = headB; 13 | int length_a = 1; 14 | int length_b = 1; 15 | int i = 0; 16 | if(curA == NULL || curB == NULL){ 17 | return NULL; 18 | } 19 | while(curA->next != NULL){ 20 | curA = curA->next; 21 | length_a++; 22 | } 23 | while(curB->next != NULL){ 24 | curB = curB->next; 25 | length_b++; 26 | } 27 | if(curA != curB){ 28 | return NULL; 29 | } 30 | curA = headA; 31 | curB = headB; 32 | if(length_a > length_b){ 33 | for(i; i < length_a-length_b; i++){ 34 | curA = curA->next; 35 | } 36 | i = 0; 37 | } 38 | else if(length_a < length_b){ 39 | for(i; i < length_b-length_a; i++){ 40 | curB = curB->next; 41 | } 42 | i = 0; 43 | } 44 | while(curA != curB){ 45 | curA = curA->next; 46 | curB = curB->next; 47 | } 48 | return curA; 49 | } -------------------------------------------------------------------------------- /Linked List/Easy/160.Intersection of Two Linked Lists/Intersection of Two Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 | ListNode *curA, *curB; 13 | curA = headA; 14 | curB = headB; 15 | if(curA == NULL || curB == NULL){ 16 | return NULL; 17 | } 18 | int length_a = getLength(curA); 19 | int length_b = getLength(curB); 20 | if(length_a > length_b){ 21 | for(int i=0; i < length_a-length_b; i++){ 22 | curA = curA->next; 23 | } 24 | } 25 | else if(length_a < length_b){ 26 | for(int i=0; i < length_b-length_a; i++){ 27 | curB = curB->next; 28 | } 29 | } 30 | while(curA != curB){ 31 | curA = curA->next; 32 | curB = curB->next; 33 | } 34 | return curA; 35 | } 36 | private: 37 | int getLength(ListNode *head){ 38 | int length = 1; 39 | while(head->next != NULL){ 40 | head = head->next; 41 | length++; 42 | } 43 | return length; 44 | } 45 | }; -------------------------------------------------------------------------------- /Linked List/Easy/160.Intersection of Two Linked Lists/Intersection of Two Linked Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def getIntersectionNode(self, headA, headB): 9 | """ 10 | :type head1, head1: ListNode 11 | :rtype: ListNode 12 | """ 13 | if headA is None or headB is None: 14 | return None 15 | 16 | pa = headA # 2 pointers 17 | pb = headB 18 | 19 | while pa is not pb: 20 | # pa先遍历headA,然后再遍历headB 21 | # pb先遍历headB,然后再遍历headA 22 | pa = headB if pa is None else pa.next 23 | pb = headA if pb is None else pb.next 24 | 25 | return pa # 只有两种方式结束循环,一种是pa和pb所指相同,另一种是headA和headB都已经遍历完仍然没有找到。 26 | -------------------------------------------------------------------------------- /Linked List/Easy/203.Remove Linked List Elements/Remove Linked List Elements.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode* removeElements(struct ListNode* head, int val) { 9 | struct ListNode *pre = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 | struct ListNode *cur = (struct ListNode *)malloc(sizeof(struct ListNode)); 11 | struct ListNode *newlist = (struct ListNode *)malloc(sizeof(struct ListNode)); 12 | newlist->next = head; 13 | pre = newlist; 14 | cur = head; 15 | while(cur != NULL){ 16 | if(cur->val == val){ 17 | cur = cur->next; 18 | pre->next = cur; 19 | } 20 | else{ 21 | pre = cur; 22 | cur = cur->next; 23 | } 24 | } 25 | return newlist->next; 26 | } -------------------------------------------------------------------------------- /Linked List/Easy/203.Remove Linked List Elements/Remove Linked List Elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeElements(ListNode* head, int val) { 12 | ListNode **list = &head; 13 | 14 | while (*list != nullptr) 15 | { 16 | if ((*list)->val == val) 17 | { 18 | *list = (*list)->next; 19 | } 20 | else 21 | { 22 | list = &(*list)->next; 23 | } 24 | } 25 | 26 | return head; 27 | } 28 | }; -------------------------------------------------------------------------------- /Linked List/Easy/206.Reverse Linked List/Reverse Linked List-iteratively.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode* reverseList(struct ListNode* head) { 9 | struct ListNode* pre = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 | struct ListNode* cur = (struct ListNode *)malloc(sizeof(struct ListNode)); 11 | struct ListNode* temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 12 | if(head == NULL || head->next == NULL){ 13 | return head; 14 | } 15 | pre = head; 16 | cur = head->next; 17 | pre->next = NULL; 18 | while(cur != NULL){ 19 | temp = cur->next; 20 | cur->next = pre; 21 | pre = cur; 22 | cur = temp; 23 | } 24 | return pre; 25 | } 26 | -------------------------------------------------------------------------------- /Linked List/Easy/206.Reverse Linked List/Reverse Linked List-recursively.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/Linked List/Easy/206.Reverse Linked List/Reverse Linked List-recursively.c -------------------------------------------------------------------------------- /Linked List/Easy/206.Reverse Linked List/Reverse Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def reverseList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | pre = None 14 | while head: 15 | cur = head 16 | head = head.next 17 | cur.next = pre 18 | pre = cur 19 | return pre 20 | -------------------------------------------------------------------------------- /Linked List/Easy/21.Merge Two Sorted Lists/Merge Two Sorted Lists.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { 9 | struct ListNode* newlist = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 | struct ListNode* temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 11 | newlist = temp; 12 | while(l1 && l2){ 13 | if(l1->val < l2->val){ 14 | temp->next = l1; 15 | l1 = l1->next; 16 | } 17 | else{ 18 | temp->next = l2; 19 | l2 = l2->next; 20 | } 21 | temp = temp->next; 22 | } 23 | temp->next = l1 ? l1 : l2; 24 | return newlist->next; 25 | } -------------------------------------------------------------------------------- /Linked List/Easy/21.Merge Two Sorted Lists/Merge Two Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 | ListNode newlist(INT_MIN); 13 | ListNode *temp = &newlist; 14 | if(l1 == NULL && l2 == NULL){ 15 | return NULL; 16 | } 17 | if(l1 != NULL && l2 == NULL){ 18 | return l1; 19 | } 20 | if(l1 == NULL && l2 != NULL){ 21 | return l2; 22 | } 23 | while(l1 && l2){ 24 | if(l1->val < l2->val){ 25 | temp->next = l1; 26 | l1 = l1->next; 27 | } 28 | else{ 29 | temp->next = l2; 30 | l2 = l2->next; 31 | } 32 | temp = temp->next; 33 | } 34 | temp->next = l1 ? l1 : l2; 35 | return newlist.next; 36 | } 37 | }; -------------------------------------------------------------------------------- /Linked List/Easy/21.Merge Two Sorted Lists/Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def mergeTwoLists(self, l1, l2): 9 | """ 10 | :type l1: ListNode 11 | :type l2: ListNode 12 | :rtype: ListNode 13 | """ 14 | result = cur = ListNode(0) 15 | while l1 and l2: 16 | if l1.val < l2.val: 17 | cur.next = l1 18 | l1 = l1.next 19 | else: 20 | cur.next = l2 21 | l2 = l2.next 22 | cur = cur.next 23 | cur.next = l1 or l2 24 | return result.next -------------------------------------------------------------------------------- /Linked List/Easy/234.Palindrome Linked List/Palindrome Linked List.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode* reverseList(struct ListNode* head) { 9 | struct ListNode* pre = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 | struct ListNode* next = (struct ListNode *)malloc(sizeof(struct ListNode)); 11 | pre=NULL; 12 | next=NULL; 13 | while(head!=NULL){ 14 | next=head->next; 15 | head->next=pre; 16 | pre=head; 17 | head=next; 18 | } 19 | return pre; 20 | } 21 | 22 | bool isPalindrome(struct ListNode* head) { 23 | struct ListNode* slow = (struct ListNode *)malloc(sizeof(struct ListNode)); 24 | struct ListNode* fast = (struct ListNode *)malloc(sizeof(struct ListNode)); 25 | if(head == NULL || head->next == NULL){ 26 | return true; 27 | } 28 | fast = head; 29 | slow = head; 30 | while(fast->next && fast->next->next){ 31 | slow = slow->next; 32 | fast = fast->next->next; 33 | } 34 | slow = reverseList(slow->next); 35 | while(slow){ 36 | if(head->val != slow->val){ 37 | return false; 38 | } 39 | head = head->next; 40 | slow = slow->next; 41 | } 42 | return true; 43 | } -------------------------------------------------------------------------------- /Linked List/Easy/234.Palindrome Linked List/Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool isPalindrome(ListNode* head) { 12 | if(head == NULL || head->next == NULL){ 13 | return true; 14 | } 15 | ListNode* slow = head; 16 | ListNode* fast = head; 17 | while(fast->next && fast->next->next){ 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | } 21 | slow = reverseList(slow->next); 22 | while(slow){ 23 | if(head->val != slow->val){ 24 | return false; 25 | } 26 | head = head->next; 27 | slow = slow->next; 28 | } 29 | return true; 30 | } 31 | ListNode* reverseList(ListNode* head){ 32 | ListNode* pre = NULL; 33 | ListNode* next = NULL; 34 | while(head!=NULL){ 35 | next=head->next; 36 | head->next=pre; 37 | pre=head; 38 | head=next; 39 | } 40 | return pre; 41 | } 42 | }; -------------------------------------------------------------------------------- /Linked List/Easy/234.Palindrome Linked List/Palindrome.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def isPalindrome(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: bool 12 | """ 13 | vals = [] 14 | while head: 15 | vals.append(head.val) 16 | head = head.next 17 | return vals == vals[::-1] -------------------------------------------------------------------------------- /Linked List/Easy/237.Delete Node in a Linked List/Delete Node in a Linked List.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | void deleteNode(struct ListNode* node) { 9 | *node = *node->next; 10 | } -------------------------------------------------------------------------------- /Linked List/Easy/237.Delete Node in a Linked List/Delete Node in a Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | node.val = node.next.val 14 | node.next = node.next.next -------------------------------------------------------------------------------- /Linked List/Easy/83.Remove Duplicates from Sorted List/Remove Duplicates from Sorted List.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | struct ListNode* deleteDuplicates(struct ListNode* head) { 9 | struct ListNode* cur = (int *)malloc(sizeof(struct ListNode)); 10 | cur = head; 11 | while(cur != NULL){ 12 | while(cur->next != NULL && cur->val == cur->next->val){ 13 | cur->next = cur->next->next; 14 | } 15 | cur = cur->next; 16 | } 17 | return head; 18 | } -------------------------------------------------------------------------------- /Linked List/Easy/83.Remove Duplicates from Sorted List/Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* deleteDuplicates(ListNode* head) { 12 | ListNode* cur = head; 13 | while(cur != NULL){ 14 | while(cur->next != NULL && cur->val == cur->next->val){ 15 | cur->next = cur->next->next; 16 | } 17 | cur = cur->next; 18 | } 19 | return head; 20 | } 21 | }; -------------------------------------------------------------------------------- /Linked List/Easy/83.Remove Duplicates from Sorted List/Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteDuplicates(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | now = head 14 | while head: 15 | while head.next and head.val == head.next.val: 16 | head.next = head.next.next 17 | 18 | head = head.next 19 | return now -------------------------------------------------------------------------------- /Linked List/Medium/1367.Linked List in Binary Tree: -------------------------------------------------------------------------------- 1 | QUESTION : 2 | Given a binary tree root and a linked list with head as the first node. 3 | Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. 4 | In this context downward path means a path that starts at some node and goes downwards. 5 | 6 | Example 1: 7 | Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 8 | Output: true 9 | Explanation: Nodes in blue form a subpath in the binary Tree. 10 | 11 | Example 2: 12 | Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 13 | Output: true 14 | 15 | Example 3: 16 | Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] 17 | Output: false 18 | Explanation: There is no path in the binary tree that contains all the elements of the linked list from head. 19 | 20 | Constraints: 21 | 1 <= node.val <= 100 for each node in the linked list and binary tree. 22 | The given linked list will contain between 1 and 100 nodes. 23 | The given binary tree will contain between 1 and 2500 nodes. 24 | 25 | C++ SOLUTION : 26 | 27 | class Solution { 28 | public: 29 | bool isSubPath(ListNode* head, TreeNode* root) { 30 | if(root){ 31 | if(isEqual(head, root)){ 32 | return true; 33 | } 34 | return isSubPath(head, root->left) || isSubPath(head, root->right); 35 | } 36 | return false; 37 | } 38 | bool isEqual(ListNode* head, TreeNode* root){ 39 | if(!head){ 40 | return true; 41 | } 42 | if(!root){ 43 | return false; 44 | } 45 | return head->val == root->val && (isEqual(head->next, root->left) || isEqual(head->next, root->right)); 46 | } 47 | }; 48 | 49 | PYTHON SOLUTION : 50 | 51 | def isSubPath(self, head: ListNode, root: TreeNode) -> bool: 52 | target = "" 53 | while head: 54 | target = target + str(head.val) 55 | head = head.next 56 | 57 | def dfs(root, path): 58 | if target in path: 59 | return True 60 | 61 | if root.left: 62 | ans = dfs(root.left, path + str(root.left.val)) 63 | if ans == True: 64 | return True 65 | 66 | if root.right: 67 | ans = dfs(root.right, path + str(root.right.val)) 68 | if ans == True: 69 | return True 70 | 71 | return False 72 | 73 | return dfs(root, str(root.val)) 74 | -------------------------------------------------------------------------------- /Linked List/Medium/2.Add Two Numbers.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定两个非空链表,结点元素为非负整数,这些数字从小到大排列。将对应结点的两个数字相加,并返回一个新链表。 4 | 5 | 假设两个链表不以0打头。 6 | 7 | **举例:** 8 | 9 | ``` stylus 10 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 11 | Output: 7 -> 0 -> 8 12 | ``` 13 | 14 | # 思路 15 | 16 | 对应位置元素相加,注意进位即可。使用divmod函数进行计算即可,很简单。 17 | 18 | # 代码 19 | 20 | **Python:** 21 | 22 | ``` python 23 | # Definition for singly-linked list. 24 | # class ListNode(object): 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.next = None 28 | 29 | class Solution(object): 30 | def addTwoNumbers(self, l1, l2): 31 | """ 32 | :type l1: ListNode 33 | :type l2: ListNode 34 | :rtype: ListNode 35 | """ 36 | extra = 0 37 | root = n = ListNode(0) 38 | while l1 or l2 or extra: 39 | v1 = v2 = 0 40 | if l1: 41 | v1 = l1.val 42 | l1 = l1.next 43 | if l2: 44 | v2 = l2.val 45 | l2 = l2.next 46 | extra, val = divmod(v1 + v2 + extra, 10) 47 | n.next = ListNode(val) 48 | n = n.next 49 | return root.next 50 | ``` 51 | 52 | **C++:** 53 | 54 | ``` cpp 55 | /** 56 | * Definition for singly-linked list. 57 | * struct ListNode { 58 | * int val; 59 | * ListNode *next; 60 | * ListNode(int x) : val(x), next(NULL) {} 61 | * }; 62 | */ 63 | class Solution { 64 | public: 65 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 66 | ListNode preHead(0), *p = &preHead; 67 | int extra = 0; 68 | while (l1 || l2 || extra) { 69 | int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; 70 | extra = sum / 10; 71 | p->next = new ListNode(sum % 10); 72 | p = p->next; 73 | l1 = l1 ? l1->next : l1; 74 | l2 = l2 ? l2->next : l2; 75 | } 76 | return preHead.next; 77 | } 78 | }; 79 | ``` 80 | 81 | 82 | -------------------------------------------------------------------------------- /Linked List/Medium/61.Rotate List/Rotate List.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/Linked List/Medium/61.Rotate List/Rotate List.c -------------------------------------------------------------------------------- /Linked List/Medium/61.Rotate List/Rotate List.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/Linked List/Medium/61.Rotate List/Rotate List.cpp -------------------------------------------------------------------------------- /Linked List/Medium/61.Rotate List/Rotate List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | 8 | class Solution(object): 9 | def rotateRight(self, head, k): 10 | """ 11 | :type head: ListNode 12 | :type k: int 13 | :rtype: ListNode 14 | """ 15 | if not head: 16 | return None 17 | tail = head 18 | listlength = 1 19 | while tail.next: 20 | tail = tail.next 21 | listlength += 1 22 | k = k % listlength 23 | if k == 0: 24 | return head 25 | k = listlength - k 26 | tail.next = head 27 | newlist = head 28 | for each in range(k - 1): 29 | newlist = newlist.next 30 | head = newlist.next 31 | newlist.next = None 32 | return head -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | 原创文章每周最少两篇,**后续最新文章**会在[【公众号】](https://cuijiahua.com/wp-content/uploads/2020/05/gzh-w.jpg)首发,视频[【B站】](https://space.bilibili.com/331507846)首发,大家可以加我[【微信】](https://cuijiahua.com/wp-content/uploads/2020/05/gzh-w.jpg)进**交流群**,技术交流或提意见都可以,欢迎**Star**! 4 | 5 |

6 | 微信群 7 | 公众号 8 | B站 9 | 知乎 10 | CSDN 11 | 头条 12 | 掘金 13 |

14 | 15 | ## 帮助文档 16 | 17 | 帮助文档存放在Help文件夹下。 18 | 19 | | 文件名 | 文件描述 | 链接 | 20 | | :---------: | :----------: | :------------------------------: | 21 | |complexitypython.txt|Python的一些常规操作的复杂度统计|[URL](https://github.com/Jack-Cherish/LeetCode/blob/master/Help/complexitypython.txt "悬停显示")| 22 | 23 | ## 题目清单 24 | 25 | 题目清单根据题目类型、难度进行排序,符号`*`代表与上下表格合并。 26 | 27 | ### Array(数组) 28 | 29 | | ID | Difficulty | Title | Python | C++ | Blog | 30 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 31 | | 1 | Easy | Two Sum | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Array/Easy/1.Two%20Sum.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/Array/Easy/1.Two%20Sum.md "悬停显示") | 32 | | 11 | Medium | Container With Most Water | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Array/Medium/11.Container%20With%20Most%20Water.md "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Array/Medium/11.Container%20With%20Most%20Water.md "悬停显示") | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/Array/Medium/11.Container%20With%20Most%20Water.md "悬停显示") | 33 | 34 | ### Linked List(链表) 35 | 36 | | ID | Difficulty | Title | Python | C++ | Blog | 37 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 38 | | 21 | Easy | Merge Two Sorted Lists | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/21.Merge%20Two%20Sorted%20Lists/Merge%20Two%20Sorted%20Lists.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/21.Merge%20Two%20Sorted%20Lists/Merge%20Two%20Sorted%20Lists.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/65449271 "悬停显示") | 39 | | 83 | * | Remove Duplicates from Sorted List | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/83.Remove%20Duplicates%20from%20Sorted%20List/Remove%20Duplicates%20from%20Sorted%20List.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/83.Remove%20Duplicates%20from%20Sorted%20List/Remove%20Duplicates%20from%20Sorted%20List.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/55106317 "悬停显示") | 40 | | 141 | * | Linked List Cycle | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/141.Linked%20List%20Cycle/Linked%20List%20Cycle.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/141.Linked%20List%20Cycle/Linked%20List%20Cycle.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/55054315 "悬停显示") | 41 | | 160 | * | Intersection of Two Linked Lists | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/160.Intersection%20of%20Two%20Linked%20Lists/Intersection%20of%20Two%20Linked%20Lists.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/160.Intersection%20of%20Two%20Linked%20Lists/Intersection%20of%20Two%20Linked%20Lists.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/56036016 "悬停显示") | 42 | | 203 | * | Remove Linked List Elements | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/203.Remove%20Linked%20List%20Elements/Remove%20Linked%20List%20Elements.cpp "悬停显示") | no | 43 | | 206 | * | Reverse Linked List | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/206.Reverse%20Linked%20List/Reverse%20Linked%20List.py "悬停显示") | [C-迭代](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/206.Reverse%20Linked%20List/Reverse%20Linked%20List-iteratively.c "悬停显示") [C-递归](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/206.Reverse%20Linked%20List/Reverse%20Linked%20List-recursively.c "悬停显示")| [博客思路讲解](http://blog.csdn.net/c406495762/article/details/60884576 "悬停显示") | 44 | | 234 | * | Palindrome Linked List | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/234.Palindrome%20Linked%20List/Palindrome.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/234.Palindrome%20Linked%20List/Palindrome%20Linked%20List.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/64443419 "悬停显示") | 45 | | 237 | Easy | Delete Node in a Linked List | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/237.Delete%20Node%20in%20a%20Linked%20List/Delete%20Node%20in%20a%20Linked%20List.py "悬停显示") | [C](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Easy/237.Delete%20Node%20in%20a%20Linked%20List/Delete%20Node%20in%20a%20Linked%20List.c "悬停显示") | no | 46 | | 2 | Medium | Add Two Numbers | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Medium/2.Add%20Two%20Numbers.md "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Medium/2.Add%20Two%20Numbers.md "悬停显示") | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Medium/2.Add%20Two%20Numbers.md "悬停显示") | 47 | | 61 | Medium | Rotate | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Medium/61.Rotate%20List/Rotate%20List.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Linked%20List/Medium/61.Rotate%20List/Rotate%20List.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/65626314 "悬停显示") | 48 | 49 | ### Stack(栈) 50 | 51 | | ID | Difficulty | Title | Python | C++ | Blog | 52 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 53 | | 20 | Easy | Valid Parentheses | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Easy/20.Valid%20Parentheses/Valid%20Parentheses.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/70154279 "悬停显示") | 54 | | 155 | * | Min Stack | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Easy/155.Min%20Stack/Min%20Stack.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/69372722 "悬停显示") | 55 | | 255 | * | Implement Stack using Queues | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Easy/225.Implement%20Stack%20using%20Queues/Implement%20Stack%20using%20Queues.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/67656851 "悬停显示") | 56 | | 232 | * | Implement Queue using Stacks | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Easy/232.Implement%20Queue%20using%20Stacks/Implement%20Queue%20using%20Stacks.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/70149075 "悬停显示") | 57 | | 496 | Easy | Next Greater Element I | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Easy/496.Next%20Greater%20Element%20I/Next%20Greater%20Element%20I.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/69359406 "悬停显示") | 58 | | 150 | Medium | Evaluate Reverse Polish Notation | no | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Stack/Medium/150.Evaluate%20Reverse%20Polish%20Notation/Evaluate%20Reverse%20Polish%20Notation.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/70233695 "悬停显示") | 59 | 60 | ### String(字符串) 61 | 62 | | ID | Difficulty | Title | Python | C++ | Blog | 63 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 64 | | 13 | Easy | Roman to Integer | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/13.Roman%20to%20Integer/Roman%20to%20Integer.py "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/tree/master/String/Easy/13.Roman%20to%20Integer "悬停显示") | 65 | | 14 | * | Longest Common Prefix | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/14.Longest%20Common%20Prefix/Longest%20Common%20Prefix.py "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/tree/master/String/Easy/14.Longest%20Common%20Prefix "悬停显示") | 66 | | 28 | * | Implement strStr | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/28.Implement%20strStr.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/28.Implement%20strStr.md "悬停显示") | 67 | | 38 | * | Count and Say | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/38.Count%20and%20Say/Count%20and%20Say.py "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/tree/master/String/Easy/38.Count%20and%20Say "悬停显示") | 68 | | 125 | * | Valid Palindrome | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/125.Valid%20Palindrome.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/125.Valid%20Palindrome.md "悬停显示") | 69 | | 150 | * | Add Binary | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/67.Add%20Binary/Add%20Binary.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/67.Add%20Binary/67.Add%20Binary.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/72519117 "悬停显示") | 70 | | 344 | * | Reverse String | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/344.Reverse%20String/Reverse%20String.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/344.Reverse%20String/Reverse%20String.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/70833096 "悬停显示") | 71 | | 345 | * | Reverse Vowels of a String | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/345.Reverse%20Vowels%20of%20a%20String.md "悬停显示") | no | [博客思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/345.Reverse%20Vowels%20of%20a%20String.md "悬停显示") | 72 | | 383 | * | Ransom Note | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/383.Ransom%20Note.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/383.Ransom%20Note.md "悬停显示") | 73 | | 434 | * | Number of Segments in a String | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/434.Number%20of%20Segments%20in%20a%20String/Number%20of%20Segments%20in%20a%20String.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/434.Number%20of%20Segments%20in%20a%20String/Number%20of%20Segments%20in%20a%20String.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/71786453 "悬停显示") | 74 | | 520 | * | Detect Capital | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/520.Detect%20Capital/Detect%20Capital.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/520.Detect%20Capital/Detect%20Capital.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/73495803 "悬停显示") | 75 | | 521 | * | Longest Uncommon Subsequence I | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/521.Longest%20Uncommon%20Subsequence%20I/Longest%20Uncommon%20Subsequence%20I.py "悬停显示") | no | no | 76 | | 541 | * | Reverse String II | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/541.Reverse%20String%20II/Reverse%20String%20II.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/541.Reverse%20String%20II/Reverse%20String%20II.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/70884683 "悬停显示") | 77 | | 551 | * | Student Attendance Record I | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/551.%20Student%20Attendance%20Record%20I/Student%20Attendance%20Record%20I.py "悬停显示") | no | no | 78 | | 557 | * | Reverse Words in a String III | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/557.Reverse%20Words%20in%20a%20String%20III/Reverse%20Words%20in%20a%20String%20III.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/557.Reverse%20Words%20in%20a%20String%20III/Reverse%20Words%20in%20a%20String%20III.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/73457057 "悬停显示") | 79 | | 657 | Easy | Judge Route Circle | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Easy/657.Judge%20Route%20Circle/Judge%20Route%20Circle.py "悬停显示") | no | no | 80 | | 3 | Medium | Longest Substring Without Repeating Characters | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/3.Longest%20Substring%20Without%20Repeating%20Characters.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/3.Longest%20Substring%20Without%20Repeating%20Characters.md "悬停显示") | 81 | | 5 | * | Longest Palindromic Substring | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/5.Longest%20Palindromic%20Substring.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/5.Longest%20Palindromic%20Substring.md "悬停显示") | 82 | | 17 | * | Letter Combinations of a Phone Number | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/17.Letter%20Combinations%20of%20a%20Phone%20Number.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/17.Letter%20Combinations%20of%20a%20Phone%20Number.md "悬停显示") | 83 | | 22 | * | Generate Parentheses | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/22.Generate%20Parentheses.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/22.Generate%20Parentheses.md "悬停显示") | 84 | | 43 | * | Multiply Strings | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/43.Multiply%20Strings.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/43.Multiply%20Strings.md "悬停显示") | 85 | | 609 | Medium | Find Duplicate File in System | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/609.Find%20Duplicate%20File%20in%20System.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/String/Medium/609.Find%20Duplicate%20File%20in%20System.md "悬停显示") | 86 | 87 | 88 | 89 | ### Tree(树) 90 | 91 | | ID | Difficulty | Title | Python | C++ | Blog | 92 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 93 | | 111 | Easy | Minimum Depth of Binary Tree | [Py-1](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/111.Minimum%20Depth%20of%20Binary%20Tree/Minimum%20Depth%20of%20Binary%20Tree-1.py "悬停显示") [Py-2](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/111.Minimum%20Depth%20of%20Binary%20Tree/Minimum%20Depth%20of%20Binary%20Tree-2.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/111.Minimum%20Depth%20of%20Binary%20Tree/Minimum%20Depth%20of%20Binary%20Tree.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/75043140 "悬停显示") | 94 | | 112 | * | Path Sum | [Py-1](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/112.Path%20Sum/Path%20Sum-1.py "悬停显示") [Py-2](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/112.Path%20Sum/Path%20Sum-2.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/112.Path%20Sum/Path%20Sum.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/76172233 "悬停显示") | 95 | | 235 | * | Lowest Common Ancestor of a Binary Search Tree | [Py-1](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree-1.py "悬停显示") [Py-2](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree-2.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/75497795 "悬停显示") | 96 | | 501 | * | Find Mode in Binary Search Tree | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/501.Find%20Mode%20in%20Binary%20Search%20Tree/Find%20Mode%20in%20Binary%20Search%20Tree.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/501.Find%20Mode%20in%20Binary%20Search%20Tree/Find%20Mode%20in%20Binary%20Search%20Tree.cpp "悬停显示") | [博客思路讲解](http://blog.csdn.net/c406495762/article/details/76046469 "悬停显示") | 97 | | 543 | * | Diameter of Binary Tree | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/543.Diameter%20of%20Binary%20Tree/Diameter%20of%20Binary%20Tree.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/543.Diameter%20of%20Binary%20Tree/Diameter%20of%20Binary%20Tree.cpp "悬停显示") | no | 98 | | 606 | Easy | Construct String from Binary Tree | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/606.Construct%20String%20from%20Binary%20Tree/Construct%20String%20from%20Binary%20Tree.py "悬停显示") | [C++](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Easy/606.Construct%20String%20from%20Binary%20Tree/Construct%20String%20from%20Binary%20Tree.cpp "悬停显示") | no | 99 | | 113 | Medium | Path Sum II | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Tree/Medium/113.Path%20Sum%20II/Path%20Sum%20II.py "悬停显示") | no | no | 100 | 101 | ### Hash Table(哈希表) 102 | 103 | | ID | Difficulty | Title | Python | C++ | Blog | 104 | | ---- | :--------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | 105 | | 290 | Easy | Word Pattern.mde | [Python](https://github.com/Jack-Cherish/LeetCode/blob/master/Hash%20Table/Easy/290.Word%20Pattern.md "悬停显示") | no | [思路讲解](https://github.com/Jack-Cherish/LeetCode/blob/master/Hash%20Table/Easy/290.Word%20Pattern.md "悬停显示") | 106 | 107 | # 剑指Offer(已完成) 108 | 109 | * [个人网站](http://cuijiahua.com/ "悬停显示")
110 | 111 | ### 链表(8道): 112 | 113 | * [剑指Offer(三):从尾到头打印链表](http://cuijiahua.com/blog/2017/11/basis_3.html "悬停显示") 114 | * [剑指Offer(十四):链表中倒数第k个结点](http://cuijiahua.com/blog/2017/12/basis_14.html "悬停显示") 115 | * [剑指Offer(十五):反转链表](http://cuijiahua.com/blog/2017/12/basis_15.html "悬停显示") 116 | * [剑指Offer(十六):合并两个排序的链表](http://cuijiahua.com/blog/2017/12/basis_16.html "悬停显示") 117 | * [剑指Offer(二十五):复杂链表的复制](http://cuijiahua.com/blog/2017/12/basis_25.html "悬停显示") 118 | * [剑指Offer(三十六):两个链表的第一个公共结点](http://cuijiahua.com/blog/2018/01/basis_36.html "悬停显示") 119 | * [剑指Offer(五十五):链表中环的入口结点](http://cuijiahua.com/blog/2018/01/basis_55.html "悬停显示") 120 | * [剑指Offer(五十六):删除链表中重复的结点](http://cuijiahua.com/blog/2018/01/basis_56.html "悬停显示") 121 | 122 | ### 二叉树(12道): 123 | 124 | * [剑指Offer(四):重建二叉树](http://cuijiahua.com/blog/2017/11/basis_4.html "悬停显示") 125 | * [剑指Offer(十七):树的子结构](http://cuijiahua.com/blog/2017/12/basis_17.html "悬停显示") 126 | * [剑指Offer(十八):二叉树的镜像](http://cuijiahua.com/blog/2017/12/basis_18.html "悬停显示") 127 | * [剑指Offer(二十二):从上往下打印二叉树](http://cuijiahua.com/blog/2017/12/basis_22.html "悬停显示") 128 | * [剑指Offer(二十四):二叉树中和为某一值的路径](http://cuijiahua.com/blog/2017/12/basis_24.html "悬停显示") 129 | * [剑指Offer(三十八):二叉树的深度](http://cuijiahua.com/blog/2018/01/basis_38.html "悬停显示") 130 | * [剑指Offer(三十九):平衡二叉树](http://cuijiahua.com/blog/2018/01/basis_39.html "悬停显示") 131 | * [剑指Offer(五十七):二叉树的下一个结点](http://cuijiahua.com/blog/2018/01/basis_57.html "悬停显示") 132 | * [剑指Offer(五十八):对称的二叉树](http://cuijiahua.com/blog/2018/01/basis_58.html "悬停显示") 133 | * [剑指Offer(五十九):按之字顺序打印二叉树](http://cuijiahua.com/blog/2018/01/basis_59.html "悬停显示") 134 | * [剑指Offer(六十):把二叉树打印成多行](http://cuijiahua.com/blog/2018/01/basis_60.html "悬停显示") 135 | * [剑指Offer(六十一):序列化二叉树](http://cuijiahua.com/blog/2018/01/basis_61.html "悬停显示") 136 | 137 | ### 二叉搜索树(3道): 138 | 139 | * [剑指Offer(二十三):二叉搜索树的后序遍历序列](http://cuijiahua.com/blog/2017/12/basis_23.html "悬停显示") 140 | * [剑指Offer(二十六):二叉搜索树与双向链表](http://cuijiahua.com/blog/2017/12/basis_26.html "悬停显示") 141 | * [剑指Offer(六十二):二叉搜索树的第k个结点](http://cuijiahua.com/blog/2018/01/basis_62.html "悬停显示") 142 | 143 | ### 数组(11道): 144 | 145 | * [剑指Offer(一):二维数组中的查找](http://cuijiahua.com/blog/2017/11/basis_1.html "悬停显示") 146 | * [剑指Offer(六):旋转数组的最小数字](http://cuijiahua.com/blog/2017/11/basis_6.html "悬停显示") 147 | * [剑指Offer(十三):调整数组顺序使奇数位于偶数前面](http://cuijiahua.com/blog/2017/11/basis_13.html "悬停显示") 148 | * [剑指Offer(二十八):数组中出现次数超过一半的数字](http://cuijiahua.com/blog/2017/12/basis_28.html "悬停显示") 149 | * [剑指Offer(三十):连续子数组的最大和](http://cuijiahua.com/blog/2017/12/basis_30.html "悬停显示") 150 | * [剑指Offer(三十二):把数组排成最小的数](http://cuijiahua.com/blog/2018/01/basis_32.html "悬停显示") 151 | * [剑指Offer(三十五):数组中的逆序对](http://cuijiahua.com/blog/2018/01/basis_35.html "悬停显示") 152 | * [剑指Offer(三十七):数字在排序数组中出现的次数](http://cuijiahua.com/blog/2018/01/basis_37.html "悬停显示") 153 | * [剑指Offer(四十):数组中只出现一次的数字](http://cuijiahua.com/blog/2018/01/basis_40.html "悬停显示") 154 | * [剑指Offer(五十):数组中重复的数字](http://cuijiahua.com/blog/2018/01/basis_50.html "悬停显示") 155 | * [剑指Offer(五十一):构建乘积数组](http://cuijiahua.com/blog/2018/01/basis_51.html "悬停显示") 156 | 157 | ### 字符串(8道): 158 | * [剑指Offer(二):替换空格](http://cuijiahua.com/blog/2017/11/basis_2.html "悬停显示") 159 | * [剑指Offer(二十七):字符串的排列](http://cuijiahua.com/blog/2017/12/basis_27.html "悬停显示") 160 | * [剑指Offer(三十四):第一个只出现一次的字符](http://cuijiahua.com/blog/2018/01/basis_34.html "悬停显示") 161 | * [剑指Offer(四十三):左旋转字符串](http://cuijiahua.com/blog/2018/01/basis_43.html "悬停显示") 162 | * [剑指Offer(四十四):翻转单词顺序序列](http://cuijiahua.com/blog/2018/01/basis_44.html "悬停显示") 163 | * [剑指Offer(四十九):把字符串转换成整数](http://cuijiahua.com/blog/2018/01/basis_49.html "悬停显示") 164 | * [剑指Offer(五十二):正则表达式匹配](http://cuijiahua.com/blog/2018/01/basis_52.html "悬停显示") 165 | * [剑指Offer(五十三):表示数值的字符串](http://cuijiahua.com/blog/2018/01/basis_53.html "悬停显示") 166 | 167 | ### 栈(3道): 168 | 169 | * [剑指Offer(五):用两个栈实现队列](http://cuijiahua.com/blog/2017/11/basis_5.html "悬停显示") 170 | * [剑指Offer(二十):包含min函数的栈](http://cuijiahua.com/blog/2017/12/basis_20.html "悬停显示") 171 | * [剑指Offer(二十一):栈的压入、弹出序列](http://cuijiahua.com/blog/2017/12/basis_21.html "悬停显示") 172 | 173 | ### 递归(4道): 174 | 175 | * [剑指Offer(七):裴波那契数列](http://cuijiahua.com/blog/2017/11/basis_7.html "悬停显示") 176 | * [剑指Offer(八):跳台阶](http://cuijiahua.com/blog/2017/11/basis_8.html "悬停显示") 177 | * [剑指Offer(九):变态跳台阶](http://cuijiahua.com/blog/2017/11/basis_9.html "悬停显示") 178 | * [剑指Offer(十):矩形覆盖](http://cuijiahua.com/blog/2017/11/basis_10.html "悬停显示") 179 | 180 | ### 回溯法(2道): 181 | 182 | * [剑指Offer(六十五):矩阵中的路径](http://cuijiahua.com/blog/2018/02/basis_65.html "悬停显示") 183 | * [剑指Offer(六十六):机器人的运动范围](http://cuijiahua.com/blog/2018/02/basis_66.html "悬停显示") 184 | 185 | ### 其他(15道): 186 | 187 | * [剑指Offer(十一):二进制中1的个数](http://cuijiahua.com/blog/2017/11/basis_11.html "悬停显示") 188 | * [剑指Offer(十二):数值的整数次方](http://cuijiahua.com/blog/2017/11/basis_12.html "悬停显示") 189 | * [剑指Offer(十九):顺时针打印矩阵](http://cuijiahua.com/blog/2017/12/basis_19.html "悬停显示") 190 | * [剑指Offer(二十九):最小的K个数](http://cuijiahua.com/blog/2017/12/basis_29.html "悬停显示") 191 | * [剑指Offer(三十一):整数中1出现的次数(从1到n整数中1出现的次数)](http://cuijiahua.com/blog/2017/12/basis_31.html "悬停显示") 192 | * [剑指Offer(三十三):丑数](http://cuijiahua.com/blog/2018/01/basis_33.html "悬停显示") 193 | * [剑指Offer(四十一):和为S的连续正数序列](http://cuijiahua.com/blog/2018/01/basis_41.html "悬停显示") 194 | * [剑指Offer(四十二):和为S的两个数字](http://cuijiahua.com/blog/2018/01/basis_42.html "悬停显示") 195 | * [剑指Offer(四十五):扑克牌顺子](http://cuijiahua.com/blog/2018/01/basis_45.html "悬停显示") 196 | * [剑指Offer(四十六):孩子们的游戏(圆圈中最后剩下的数)](http://cuijiahua.com/blog/2018/01/basis_46.html "悬停显示") 197 | * [剑指Offer(四十七):求1+2+3+…+n](http://cuijiahua.com/blog/2018/01/basis_47.html "悬停显示") 198 | * [剑指Offer(四十八):不用加减乘除的加法](http://cuijiahua.com/blog/2018/01/basis_48.html "悬停显示") 199 | * [剑指Offer(五十四):字符流中第一个不重复的字符](http://cuijiahua.com/blog/2018/01/basis_54.html "悬停显示") 200 | * [剑指Offer(六十三):数据流中的中位数](http://cuijiahua.com/blog/2018/02/basis_63.html "悬停显示") 201 | * [剑指Offer(六十四):滑动窗口的最大值](http://cuijiahua.com/blog/2018/02/basis_64.html "悬停显示") 202 | 203 | 更多精彩,敬请期待! 204 | 205 | 206 | 207 | wechat 208 | -------------------------------------------------------------------------------- /Stack/Easy/155.Min Stack/Min Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | stack all_stk; 5 | stack min_stk; 6 | 7 | void push(int x) { 8 | all_stk.push(x); 9 | if(min_stk.empty() || min_stk.top() >= x){ 10 | min_stk.push(x); 11 | } 12 | } 13 | void pop() { 14 | if(all_stk.top() == min_stk.top()){ 15 | min_stk.pop(); 16 | } 17 | all_stk.pop(); 18 | } 19 | 20 | int top() { 21 | if(all_stk.empty()){ 22 | return 0; 23 | } 24 | else{ 25 | return all_stk.top(); 26 | } 27 | } 28 | 29 | int getMin() { 30 | if(min_stk.empty()){ 31 | return 0; 32 | } 33 | else{ 34 | return min_stk.top(); 35 | } 36 | } 37 | }; 38 | 39 | /** 40 | * Your MinStack object will be instantiated and called as such: 41 | * MinStack obj = new MinStack(); 42 | * obj.push(x); 43 | * obj.pop(); 44 | * int param_3 = obj.top(); 45 | * int param_4 = obj.getMin(); 46 | */ -------------------------------------------------------------------------------- /Stack/Easy/20.Valid Parentheses/Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack stk; 5 | for(char c : s){ 6 | switch(c){ 7 | case '(': 8 | case '[': 9 | case '{':stk.push(c);break; 10 | case ')':if(stk.empty() || stk.top() != '(') return false;else stk.pop();break; 11 | case ']':if(stk.empty() || stk.top() != '[') return false;else stk.pop();break; 12 | case '}':if(stk.empty() || stk.top() != '{') return false;else stk.pop();break; 13 | default:break; 14 | } 15 | } 16 | return stk.empty(); 17 | } 18 | }; -------------------------------------------------------------------------------- /Stack/Easy/225.Implement Stack using Queues/Implement Stack using Queues.cpp: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | public: 3 | /** Initialize your data structure here. */ 4 | MyStack() { 5 | } 6 | 7 | queue que; 8 | 9 | /** Push element x onto stack. */ 10 | void push(int x) { 11 | que.push(x); 12 | for(int i=0; i< que.size()-1; i++){ 13 | que.push(que.front()); 14 | que.pop(); 15 | } 16 | } 17 | 18 | /** Removes the element on top of the stack and returns that element. */ 19 | int pop() { 20 | int i = que.front(); 21 | que.pop(); 22 | return i; 23 | } 24 | 25 | /** Get the top element. */ 26 | int top() { 27 | return que.front(); 28 | } 29 | 30 | /** Returns whether the stack is empty. */ 31 | bool empty() { 32 | return que.empty(); 33 | } 34 | }; 35 | 36 | /** 37 | * Your MyStack object will be instantiated and called as such: 38 | * MyStack obj = new MyStack(); 39 | * obj.push(x); 40 | * int param_2 = obj.pop(); 41 | * int param_3 = obj.top(); 42 | * bool param_4 = obj.empty(); 43 | */ -------------------------------------------------------------------------------- /Stack/Easy/232.Implement Queue using Stacks/Implement Queue using Stacks.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | 4 | stack input, output; 5 | /** Push element x to the back of queue. */ 6 | void push(int x) { 7 | input.push(x); 8 | } 9 | /** Removes the element from in front of queue and returns that element. */ 10 | int pop() { 11 | int a = peek(); 12 | output.pop(); 13 | return a; 14 | } 15 | 16 | /** Get the front element. */ 17 | int peek() { 18 | if(output.empty()){ 19 | while(input.size()){ 20 | output.push(input.top()); 21 | input.pop(); 22 | } 23 | } 24 | return output.top(); 25 | } 26 | 27 | /** Returns whether the queue is empty. */ 28 | bool empty() { 29 | return input.empty() && output.empty(); 30 | } 31 | }; 32 | 33 | /** 34 | * Your MyQueue object will be instantiated and called as such: 35 | * MyQueue obj = new MyQueue(); 36 | * obj.push(x); 37 | * int param_2 = obj.pop(); 38 | * int param_3 = obj.peek(); 39 | * bool param_4 = obj.empty(); 40 | */ -------------------------------------------------------------------------------- /Stack/Easy/496.Next Greater Element I/Next Greater Element I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& findNums, vector& nums) { 4 | stack s; 5 | unordered_map m; 6 | //遍历nums中的元素 7 | for (auto e : nums){ 8 | //堆栈s为空并且堆栈s的栈顶的元素小于e元素,将元素写入map中,key值为栈顶元素,value值为比栈顶元素大的元素 9 | while(!s.empty() && s.top() < e){ 10 | m[s.top()] = e; 11 | s.pop(); 12 | } 13 | s.push(e); 14 | } 15 | vector ans; 16 | //查找findNums中元素,如果m中存在n,返回m[n]的valuse值,如果不存在返回-1 17 | for (auto n : findNums){ 18 | ans.push_back(m.count(n) ? m[n] : -1); 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /Stack/Medium/150.Evaluate Reverse Polish Notation/Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector& tokens) { 4 | stack s; 5 | int result, rnum, lnum; 6 | int size = tokens.size(); 7 | for(int i = 0; i < size; i++){ 8 | if(tokens[i] == "*"){ 9 | rnum = s.top(); 10 | s.pop(); 11 | lnum = s.top(); 12 | s.pop(); 13 | result = lnum * rnum; 14 | s.push(result); 15 | } 16 | else if(tokens[i] == "/"){ 17 | rnum = s.top(); 18 | s.pop(); 19 | lnum = s.top(); 20 | s.pop(); 21 | result = lnum / rnum; 22 | s.push(result); 23 | } 24 | else if(tokens[i] == "+"){ 25 | rnum = s.top(); 26 | s.pop(); 27 | lnum = s.top(); 28 | s.pop(); 29 | result = lnum + rnum; 30 | s.push(result); 31 | } 32 | else if(tokens[i] == "-"){ 33 | rnum = s.top(); 34 | s.pop(); 35 | lnum = s.top(); 36 | s.pop(); 37 | result = lnum - rnum; 38 | s.push(result); 39 | } 40 | else{ 41 | s.push(atoi(tokens[i].c_str())); 42 | } 43 | } 44 | return s.top(); 45 | } 46 | }; -------------------------------------------------------------------------------- /String/Easy/125.Valid Palindrome.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定一个字符串,判断这个字符串是不是回文。不考虑标点符合和空格以及大小写。 4 | 5 | **举例:** 6 | 7 | - "A man, a plan, a canal: Panama" 是回文 8 | - "race a car" 不是回文 9 | 10 | **Note:** 11 | 12 | - 对于空字符串,默认为回文。 13 | 14 | # 思路 15 | 16 | 很简单,使用正则表达式匹配所有字母,并将其转换为小写字母。然后收尾比对,不一样就返回False。 17 | 18 | # 代码 19 | 20 | ```python 21 | class Solution(object): 22 | def isPalindrome(self, s): 23 | """ 24 | :type s: str 25 | :rtype: bool 26 | """ 27 | s = re.findall('\w{1}', s.lower()) 28 | s_len = int(len(s) / 2) 29 | for i in range(s_len): 30 | if s[i] != s[-(i+1)]: 31 | return False 32 | return True 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /String/Easy/13.Roman to Integer/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/String/Easy/13.Roman to Integer/README.md -------------------------------------------------------------------------------- /String/Easy/13.Roman to Integer/Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1} 8 | result = 0 9 | for i in range(0, len(s) - 1): 10 | if roman[s[i]] < roman[s[i+1]]: 11 | result -= roman[s[i]] 12 | else: 13 | result += roman[s[i]] 14 | return result + roman[s[-1]] -------------------------------------------------------------------------------- /String/Easy/14.Longest Common Prefix/Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | #方法一,利用zip,更快 2 | class Solution(object): 3 | def longestCommonPrefix(self, strs): 4 | """ 5 | :type strs: List[str] 6 | :rtype: str 7 | """ 8 | if not strs: 9 | return "" 10 | 11 | for i, letter_group in enumerate(zip(*strs)): 12 | if len(set(letter_group)) > 1: 13 | return strs[0][:i] 14 | return min(strs) 15 | 16 | #方法二,利用reduce 17 | class Solution: 18 | 19 | def lcp(self, str1, str2): 20 | i = 0 21 | while (i < len(str1) and i < len(str2)): 22 | if str1[i] == str2[i]: 23 | i = i+1 24 | else: 25 | break 26 | return str1[:i] 27 | 28 | def longestCommonPrefix(self, strs): 29 | """ 30 | :type strs: List[str] 31 | :rtype: str 32 | """ 33 | if not strs: 34 | return '' 35 | else: 36 | return reduce(self.lcp,strs) -------------------------------------------------------------------------------- /String/Easy/14.Longest Common Prefix/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/String/Easy/14.Longest Common Prefix/README.md -------------------------------------------------------------------------------- /String/Easy/28.Implement strStr.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 判断needle字符串在haystack字符串第一次出现的位置,没有出现返回-1。 4 | 5 | **举例:** 6 | 7 | - haystack = 'I love you baby!',needle = 'you',返回7 8 | - haystack = 'I love you baby!',needle = 'him',返回-1 9 | 10 | # 思路 11 | 12 | 使用字符串的index方法即可。 13 | 14 | # 代码 15 | 16 | ```python 17 | class Solution(object): 18 | def strStr(self, haystack, needle): 19 | """ 20 | :type haystack: str 21 | :type needle: str 22 | :rtype: int 23 | """ 24 | if needle in haystack: 25 | return haystack.index(needle) 26 | else: 27 | return -1 28 | ``` -------------------------------------------------------------------------------- /String/Easy/344.Reverse String/Reverse String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseString(string s) { 4 | int begin = 0, end = s.size() - 1; 5 | while(begin < end){ 6 | swap(s[begin++], s[end--]); 7 | } 8 | return s; 9 | } 10 | }; -------------------------------------------------------------------------------- /String/Easy/344.Reverse String/Reverse String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | return s[::-1] -------------------------------------------------------------------------------- /String/Easy/345.Reverse Vowels of a String.md: -------------------------------------------------------------------------------- 1 | ## 题目 2 | 3 | 写一个函数,输入为一个字符串。仅反转字符串中的元音。 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | ### 例如: 7 | 8 | * 输入:'hello',返回'holle' 9 | * 输入:'leetcode',返回'leotcede' 10 | * 输入:'aeiou',返回'aeiou' 11 | * 输入:'coding every day',返回'cadeng eviry doy' 12 | 13 | ### 思路: 14 | 15 | 理解要求即可,要求是将所有元音反转位置。使用re.sub替换。找原因位置,可以用正则表达式进行匹配。`(?i)[aeiou]`表示匹配原因,不区分大小写。`(?i)`为模式修饰符。 16 | 17 | ```python 18 | class Solution(object): 19 | def reverseVowels(self, s): 20 | """ 21 | :type s: str 22 | :rtype: str 23 | """ 24 | vowels = re.findall('(?i)[aeiou]', s) 25 | return re.sub('(?i)[aeiou]', lambda x: vowels.pop(), s) 26 | ``` 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /String/Easy/38.Count and Say/Count and Say.py: -------------------------------------------------------------------------------- 1 | #傻瓜式方法 2 | class Solution(object): 3 | def countAndSay(self, n): 4 | """ 5 | :type n: int 6 | :rtype: str 7 | """ 8 | s = '1' 9 | for i in range(1,n): 10 | result = [] 11 | while s: 12 | cout = {} 13 | s_len = len(s) 14 | for i in range(s_len): 15 | if s[i] != s[0]: 16 | index = i - 1 17 | break 18 | else: 19 | index = s_len - 1 20 | 21 | cout[int(s[0])] = index + 1 22 | result.append(cout) 23 | s = s[index + 1:] 24 | s = '' 25 | for each in result: 26 | s += str(list(each.values())[0]) + str(list(each.keys())[0]) 27 | return s 28 | 29 | #与傻瓜方法一样,区别在于匹配使用正则表达式匹配 30 | # r'(.)\1*'为后向引用 31 | # 表示表达式中,\1表示,从左往右数,第一个左括号对应的括号内的内容。 32 | # 以此类推,\2表示第二个,\0表示整个表达式 33 | class Solution(object): 34 | def countAndSay(self, n): 35 | """ 36 | :type n: int 37 | :rtype: str 38 | """ 39 | s = '1' 40 | for _ in range(n-1): 41 | s = re.sub(r'(.)\1*', lambda a: str(len(a.group(0))) + a.group(1), s) 42 | return s -------------------------------------------------------------------------------- /String/Easy/38.Count and Say/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jack-Cherish/LeetCode/de27c8eefd1f484ada0bc2fd506b09a9d17ff8a7/String/Easy/38.Count and Say/README.md -------------------------------------------------------------------------------- /String/Easy/383.Ransom Note.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | ``` 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 5 | 6 | Each letter in the magazine string can only be used once in your ransom note. 7 | ``` 8 | 9 | ### Note: 10 | 11 | 假设只包含小写字母 12 | ``` 13 | canConstruct("a", "b") -> false 14 | canConstruct("aa", "ab") -> false 15 | canConstruct("aa", "aab") -> true 16 | ``` 17 | 18 | # 思路 19 | 20 | 判断ransomNote中的字符在magezine出现的次数,如果ransomNote中字符出现的次数多余在magezine中出现的此处,那么返回False。 21 | 22 | ## Python 23 | 24 | ```Python 25 | class Solution(object): 26 | def canConstruct(self, ransomNote, magazine): 27 | """ 28 | :type ransomNote: str 29 | :type magazine: str 30 | :rtype: bool 31 | """ 32 | if len(ransomNote) == 0: 33 | return True 34 | for each in list(set(ransomNote)): 35 | if ransomNote.count(each) > magazine.count(each): 36 | return False 37 | return True 38 | ``` 39 | -------------------------------------------------------------------------------- /String/Easy/434.Number of Segments in a String/Number of Segments in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //去掉字符串两端的空格 4 | string& trim(string &s) { 5 | if (s.empty()) { 6 | return s; 7 | } 8 | s.erase(0, s.find_first_not_of(" ")); 9 | s.erase(s.find_last_not_of(" ") + 1); 10 | return s; 11 | } 12 | 13 | int countSegments(string s) { 14 | //字符串为空,返回0 15 | if (trim(s).empty()) { 16 | return 0; 17 | } 18 | int ans = 1; 19 | s = trim(s); 20 | for (int i = 0; i < s.length(); i++) { 21 | //当前字符和下一个字符都不为空格,则为一个字段 22 | if (s[i-1] == ' ' && s[i] != ' ') { 23 | ans++; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /String/Easy/434.Number of Segments in a String/Number of Segments in a String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countSegments(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | return len(s.split()) -------------------------------------------------------------------------------- /String/Easy/520.Detect Capital/Detect Capital.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | int cnt = 0; 5 | for(char c: word) { 6 | if('Z' - c >= 0){ 7 | cnt++; 8 | } 9 | } 10 | return ((cnt == 0 || cnt == word.length() || (cnt == 1 && 'Z' - word[0] >= 0))); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/Easy/520.Detect Capital/Detect Capital.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def detectCapitalUse(self, word): 3 | """ 4 | :type word: str 5 | :rtype: bool 6 | """ 7 | return word.isupper() or word.islower() or word.istitle() 8 | -------------------------------------------------------------------------------- /String/Easy/521.Longest Uncommon Subsequence I/Longest Uncommon Subsequence I.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLUSlength(self, a, b): 3 | """ 4 | :type a: str 5 | :type b: str 6 | :rtype: int 7 | """ 8 | if a == b: 9 | return -1 10 | return max(len(a), len(b)) -------------------------------------------------------------------------------- /String/Easy/541.Reverse String II/Reverse String II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseStr(string s, int k) { 4 | for(int i = 0; i < s.size(); i += 2*k){ 5 | reverse(s.begin()+i, min(s.begin()+i+k, s.end())); 6 | } 7 | return s; 8 | } 9 | }; -------------------------------------------------------------------------------- /String/Easy/541.Reverse String II/Reverse String II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseStr(self, s, k): 3 | """ 4 | :type s: str 5 | :type k: int 6 | :rtype: str 7 | """ 8 | s_size = len(s) 9 | result = '' 10 | for i in range(0, s_size, 2*k): 11 | temp = s[i:min([i+2*k,s_size])] 12 | result += temp[k-1::-1] + temp[k:] 13 | return result -------------------------------------------------------------------------------- /String/Easy/551. Student Attendance Record I/Student Attendance Record I.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkRecord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | if s.count('A') > 1 or s.count('LLL') > 0: 8 | return False 9 | else: 10 | return True -------------------------------------------------------------------------------- /String/Easy/557.Reverse Words in a String III/Reverse Words in a String III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | int front = 0; //记录空格后第一个字符的位置 5 | int str_length = s.length(); //字符串长度 6 | for(int i = 0; i <= str_length; i++) { 7 | if(i == s.length() || s[i] == ' ') { //找到空格反转,没有空格整个字符串反转 8 | reverse(&s[front], &s[i]); 9 | front = i + 1; 10 | } 11 | } 12 | return s; 13 | } 14 | }; -------------------------------------------------------------------------------- /String/Easy/557.Reverse Words in a String III/Reverse Words in a String III.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | result = '' 8 | input_str = s.split(' ') 9 | for each in input_str: 10 | result = result + each[::-1] + ' ' 11 | return result[:-1] 12 | 13 | # return ' '.join(x[::-1] for x in s.split()) 14 | 15 | # return ' '.join(s.split()[::-1])[::-1] -------------------------------------------------------------------------------- /String/Easy/657.Judge Route Circle/Judge Route Circle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeCircle(self, moves): 3 | """ 4 | :type moves: str 5 | :rtype: bool 6 | """ 7 | if moves.count('U') == moves.count('D') and moves.count('R') == moves.count('L'): 8 | return True 9 | else: 10 | return False -------------------------------------------------------------------------------- /String/Easy/67.Add Binary/67.Add Binary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | string s = ""; 5 | //i字符串a的索引值,j字符串b的索引值 6 | int c = 0, i = a.size() - 1, j = b.size() - 1; 7 | //字符串a和b没有遍历完,或者存在进位,继续计算 8 | while(i >= 0 || j >= 0 || c == 1) 9 | { 10 | //三目运算符:低位相加 11 | c += i >= 0 ? a[i--] - '0' : 0; 12 | c += j >= 0 ? b[j--] - '0' : 0; 13 | //结果 14 | s = char(c % 2 + '0') + s; 15 | //进位计算 16 | c /= 2; 17 | } 18 | //返回结果 19 | return s; 20 | } 21 | }; -------------------------------------------------------------------------------- /String/Easy/67.Add Binary/Add Binary.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def addBinary(self, a, b): 3 | """ 4 | :type a: str 5 | :type b: str 6 | :rtype: str 7 | """ 8 | if len(a)==0: return b 9 | if len(b)==0: return a 10 | if a[-1] == '1' and b[-1] == '1': 11 | return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1') +'0' 12 | if a[-1] == '0' and b[-1] == '0': 13 | return self.addBinary(a[0:-1],b[0:-1])+'0' 14 | else: 15 | return self.addBinary(a[0:-1],b[0:-1])+'1' -------------------------------------------------------------------------------- /String/Medium/17.Letter Combinations of a Phone Number.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定一个数字字符串,返回所有数字代表的所有字母组合结果。 4 | 5 | 数字到字母的映射,就像电话按钮一样。 6 | ```python 7 | kvmaps = { 8 | '2': 'abc', 9 | '3': 'def', 10 | '4': 'ghi', 11 | '5': 'jkl', 12 | '6': 'mno', 13 | '7': 'pqrs', 14 | '8': 'tuv', 15 | '9': 'wxyz' 16 | } 17 | ``` 18 | 19 | **例子:** 20 | 21 | Input:Digit string "23" 22 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 23 | 24 | # 思考 25 | 就是遍历所有可能组合,一个简单的方法是使用reduce函数 26 | 27 | **代码:** 28 | 29 | 普通遍历方法: 30 | 31 | ```python 32 | class Solution(object): 33 | def letterCombinations(self, digits): 34 | """ 35 | :type digits: str 36 | :rtype: List[str] 37 | """ 38 | if '' == digits: return [] 39 | kvmaps = { 40 | '2': 'abc', 41 | '3': 'def', 42 | '4': 'ghi', 43 | '5': 'jkl', 44 | '6': 'mno', 45 | '7': 'pqrs', 46 | '8': 'tuv', 47 | '9': 'wxyz' 48 | } 49 | ret=[''] 50 | for c in digits: 51 | tmp=[] 52 | for y in ret: 53 | for x in kvmaps[c]: 54 | tmp.append(y+x) 55 | ret=tmp 56 | return ret 57 | ``` 58 | 59 | 使用reduce 60 | 61 | ```python 62 | class Solution(object): 63 | def letterCombinations(self, digits): 64 | """ 65 | :type digits: str 66 | :rtype: List[str] 67 | """ 68 | if '' == digits: return [] 69 | kvmaps = { 70 | '2': 'abc', 71 | '3': 'def', 72 | '4': 'ghi', 73 | '5': 'jkl', 74 | '6': 'mno', 75 | '7': 'pqrs', 76 | '8': 'tuv', 77 | '9': 'wxyz' 78 | } 79 | return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, ['']) 80 | ``` -------------------------------------------------------------------------------- /String/Medium/22.Generate Parentheses.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 根据给定的n,写一个函数形成所有正确的括号组合。 4 | 5 | **例如:** 6 | 7 | 输入:3 8 | 输出: 9 | 10 | ```python 11 | [ 12 | "((()))", 13 | "(()())", 14 | "(())()", 15 | "()(())", 16 | "()()()" 17 | ] 18 | ``` 19 | 20 | # 思路 21 | 22 | 对我来说,这题有些费脑子,递归一直感觉学的不够好。看了大神的解法才有思路。很神奇,用Pycharm调试才懂是怎么回事。思路调试一下代码就清晰了。 23 | 24 | ```python 25 | class Solution(object): 26 | def generateParenthesis(self, n): 27 | """ 28 | :type n: int 29 | :rtype: List[str] 30 | """ 31 | def generate(p, left, right, parens=[]): 32 | if left: 33 | generate(p+'(', left-1, right) 34 | if right > left: 35 | generate(p+')', left, right-1) 36 | if not right: 37 | parens.append(p) 38 | return parens 39 | return generate('', n, n) 40 | ``` 41 | -------------------------------------------------------------------------------- /String/Medium/3.Longest Substring Without Repeating Characters.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定一个字符串,找到最长无重复子字符串。 4 | 5 | **举例:** 6 | 7 | - 给定的“abcabcbb”,答案是“abc”,长度为3。 8 | - 给定的“bbbbb”,答案是"b",长度为1。 9 | - 给定的“pwwkew”,答案是"wke",长度为3。注意是最长子字符串,不是最长子序列"pwke"。 10 | 11 | 12 | # 思路 13 | 14 | 定义两个变量longest和left,longest用于存储最长子字符串的长度,left存储无重复子串左边的起始位置。 15 | 16 | 然后创建一个哈希表,遍历整个字符串,如果字符串没有在哈希表中出现,说明没有遇到过该字符,则此时计算最长无重复子串,当哈希表中的值小于left,说明left位置更新了,需要重新计算最长无重复子串。每次在哈希表中将当前字符串对应的赋值加1。 17 | 18 | # 代码 19 | 20 | ``` python 21 | class Solution(object): 22 | def lengthOfLongestSubstring(self, s): 23 | """ 24 | :type s: str 25 | :rtype: int 26 | """ 27 | longest = 0; left = 0; tmp = {} 28 | for index, each in enumerate(s): 29 | if each not in tmp or tmp[each] < left: 30 | longest = max(longest, index - left + 1) 31 | else: 32 | left = tmp[each] 33 | tmp[each] = index + 1 34 | return longest 35 | ``` 36 | -------------------------------------------------------------------------------- /String/Medium/43.Multiply Strings.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 给定两个用字符串num1和num2表示的整数,返回它们相乘的结果。 4 | 5 | **注意:** 6 | 7 | - num1和num2的长度均小于110 8 | - num1和num2只包含0-9的数字 9 | - num1和num2不以0开头 10 | - 不能使用内联的BigInteger库,不能上来直接将num1和num2转换为int型 11 | 12 | **举例:** 13 | 14 | ``` 15 | 输入: 16 | '12', '11' 17 | 输出: 18 | '132' 19 | ``` 20 | 21 | # 分析 22 | 23 | 这题如果这么做就非常简单: 24 | 25 | ``` python 26 | class Solution(object): 27 | def multiply(self, num1, num2): 28 | """ 29 | :type num1: str 30 | :type num2: str 31 | :rtype: str 32 | """ 33 | return str(int(num1) * int(num2)) 34 | ``` 35 | 36 | 可以直接运行,也能出结果,Beats 95%以上。那是因为你没有按照人家要求玩,没意义。 37 | 38 | 这道题,我们可以使用一个列表,统计它们的计算结果。思路简单,直接上代码看吧。enumerate()很好用啊。 39 | 40 | # 代码 41 | 42 | ``` python 43 | class Solution(object): 44 | def multiply(self, num1, num2): 45 | """ 46 | :type num1: str 47 | :type num2: str 48 | :rtype: str 49 | """ 50 | res = [0] * (len(num1) + len(num2)) 51 | for i, e1 in enumerate(reversed(num1)): 52 | for j, e2 in enumerate(reversed(num2)): 53 | res[i+j] += int(e1) * int(e2) 54 | res[i+j+1] += res[i+j] // 10 55 | res[i+j] %= 10 56 | print(res) 57 | while len(res) > 1 and res[-1] == 0: 58 | res.pop() 59 | return ''.join(map(str, res[::-1])) 60 | ``` 61 | 62 | 63 | -------------------------------------------------------------------------------- /String/Medium/5.Longest Palindromic Substring.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 给定一个字符串s,找到最长回文子字符串s。假设s的最大长度为s。 3 | 4 | **举例1:** 5 | 6 | ``` 7 | 输入:"babad" 8 | 输出:"bab" 9 | 注意:"aba"也是一个有效结果。 10 | ``` 11 | 12 | **举例2:** 13 | 14 | ``` 15 | 输入:"cbbd" 16 | 输出:"bb" 17 | ``` 18 | 19 | # 思路 20 | 21 | 可以使用中心扩展的方法,把给定的每一个字母当做中心,向两边扩展,这样找到最长的子回文串。算法复杂度为O(N^2)。 22 | 分为两种情况: 23 | 24 | - aba,这样长度为奇数的回文 25 | - abba,这样长度为偶数的回文 26 | 27 | # 代码 28 | 基本方法: 29 | 30 | ``` python 31 | class Solution(object): 32 | def longestPalindrome(self, s): 33 | """ 34 | :type s: str 35 | :rtype: str 36 | """ 37 | length = len(s) 38 | maxlength = 1 39 | start = 0 40 | if length == 0: return None 41 | if length == 1: return True 42 | 43 | #奇数回文 44 | for i in range(length): 45 | j = i - 1 46 | k = i + 1 47 | while j >= 0 and k < length and s[j] == s[k]: 48 | if k - j + 1 > maxlength: 49 | maxlength = k - j + 1 50 | start = j 51 | j -= 1 52 | k += 1 53 | 54 | #偶数回文 55 | for i in range(length): 56 | j = i 57 | k = i + 1 58 | while j >= 0 and k < length and s[j] == s[k]: 59 | if k - j + 1 > maxlength: 60 | maxlength = k - j + 1 61 | start = j 62 | j -= 1 63 | k += 1 64 | 65 | if maxlength > 0: 66 | return s[start:start+maxlength] 67 | return None 68 | ``` 69 | 70 | 改进方法: 71 | 72 | ``` python 73 | class Solution(object): 74 | def longestPalindrome(self, s): 75 | """ 76 | :type s: str 77 | :rtype: str 78 | """ 79 | if len(s)==0: 80 | return 0 81 | maxLen=1 82 | start=0 83 | for i in range(len(s)): 84 | if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]: 85 | start=i-maxLen-1 86 | maxLen+=2 87 | continue 88 | 89 | if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]: 90 | start=i-maxLen 91 | maxLen+=1 92 | return s[start:start+maxLen] 93 | ``` 94 | 95 | 96 | -------------------------------------------------------------------------------- /String/Medium/609.Find Duplicate File in System.md: -------------------------------------------------------------------------------- 1 | # 题目 2 | 3 | 找到系统中重复的文件。给定一个目录信息列表,包含目录路径以及文件的内容。找出这个重复的文件的路径。 4 | 5 | **举例1:** 6 | 7 | ``` 8 | 输入: 9 | ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] 10 | 输出: 11 | [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] 12 | ``` 13 | 14 | **举例2:** 15 | 16 | ``` 17 | 输入: 18 | ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(higk)", "root/c/d 4.txt(lmn)", "root 4.txt(opq)"] 19 | 输出: 20 | [] 21 | ``` 22 | 23 | # 思路 24 | 25 | 就是输出重复内容的文件的路径,内容相同的文件放在一个列表里,最终输出的结果是列表嵌套列表的结构。如果没有内容重复 的文件,则输出空列表。 26 | 27 | 判断内容是否重复,可以使用一个技巧,用集合set()去重,如果去重的数量没变,说明没有重复的,直接输出空列表即可。 28 | 29 | # 代码 30 | 31 | ``` python 32 | class Solution(object): 33 | def findDuplicate(self, paths): 34 | """ 35 | :type paths: List[str] 36 | :rtype: List[List[str]] 37 | """ 38 | all_paths = [] 39 | for path in paths: 40 | files = [] 41 | tmp = path.split(' ') 42 | nums = len(tmp) - 1 43 | for file in tmp[1:]: 44 | all_paths.append(tmp[0] + '/' + file) 45 | contents = [] 46 | for each in all_paths: 47 | contents.append(each[each.index('(')+1:-1]) 48 | result = [] 49 | if len(set(contents)) == len(contents): 50 | return [] 51 | for content in set(contents): 52 | if contents.count(content) > 1: 53 | tmp = [] 54 | for i in range(len(contents)): 55 | if content == contents[i]: 56 | tmp.append(all_paths[i][:all_paths[i].index('(')]) 57 | result.append(tmp) 58 | return result 59 | ``` 60 | -------------------------------------------------------------------------------- /Tree/Easy/111.Minimum Depth of Binary Tree/Minimum Depth of Binary Tree-1.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def minDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if not root: 15 | return 0 16 | d = map(self.minDepth, (root.left, root.right)) 17 | return 1 + (min(d) or max(d)) -------------------------------------------------------------------------------- /Tree/Easy/111.Minimum Depth of Binary Tree/Minimum Depth of Binary Tree-2.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def minDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if not root: 15 | return 0 16 | queue = [root] 17 | height = 0 18 | while queue: 19 | # node = queue.pop(0) 20 | height += 1 21 | ls = [] 22 | for temp in queue: 23 | if not temp.right and not temp.left: 24 | return height 25 | if temp.left: 26 | ls.append(temp.left) 27 | if temp.right: 28 | ls.append(temp.right) 29 | queue = ls 30 | return height 31 | -------------------------------------------------------------------------------- /Tree/Easy/111.Minimum Depth of Binary Tree/Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int minDepth(TreeNode* root) { 13 | if(!root) return 0; 14 | int l = minDepth(root->left); 15 | int r = minDepth(root->right); 16 | return 1 + (l && r ? min(l, r) : max(l, r)); 17 | } 18 | }; -------------------------------------------------------------------------------- /Tree/Easy/112.Path Sum/Path Sum-1.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def hasPathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: bool 14 | """ 15 | if not root: 16 | return False 17 | if not root.left and not root.right and root.val == sum: 18 | return True 19 | sum -= root.val 20 | return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum) -------------------------------------------------------------------------------- /Tree/Easy/112.Path Sum/Path Sum-2.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def hasPathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: bool 14 | """ 15 | if not root: 16 | return False 17 | elif not root.left and not root.right and root.val == sum: 18 | return True 19 | for child in (root.left, root.right): 20 | if child: 21 | if self.hasPathSum(child, sum - root.val): 22 | return True 23 | return False 24 | -------------------------------------------------------------------------------- /Tree/Easy/112.Path Sum/Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool hasPathSum(TreeNode* root, int sum) { 13 | if (root == NULL) return false; 14 | else if (root->val == sum && root->left == NULL && root->right == NULL) return true; 15 | if (root->left && hasPathSum(root->left, sum - root->val)) return true; 16 | if (root->right && hasPathSum(root->right, sum - root->val)) return true; 17 | return false; 18 | } 19 | }; -------------------------------------------------------------------------------- /Tree/Easy/235.Lowest Common Ancestor of a Binary Search Tree/Lowest Common Ancestor of a Binary Search Tree-1.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def lowestCommonAncestor(self, root, p, q): 10 | """ 11 | :type root: TreeNode 12 | :type p: TreeNode 13 | :type q: TreeNode 14 | :rtype: TreeNode 15 | """ 16 | if p.val < root.val > q.val: 17 | return self.lowestCommonAncestor(root.left, p, q) 18 | elif p.val > root.val < q.val: 19 | return self.lowestCommonAncestor(root.right, p, q) 20 | else: 21 | return root 22 | 23 | -------------------------------------------------------------------------------- /Tree/Easy/235.Lowest Common Ancestor of a Binary Search Tree/Lowest Common Ancestor of a Binary Search Tree-2.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def lowestCommonAncestor(self, root, p, q): 10 | """ 11 | :type root: TreeNode 12 | :type p: TreeNode 13 | :type q: TreeNode 14 | :rtype: TreeNode 15 | """ 16 | while True: 17 | if p.val < root.val > q.val: 18 | root = root.left 19 | elif p.val > root.val < q.val: 20 | root = root.right 21 | else: 22 | return root 23 | 24 | -------------------------------------------------------------------------------- /Tree/Easy/235.Lowest Common Ancestor of a Binary Search Tree/Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if (p->val < root->val && root->val > q->val) 14 | return lowestCommonAncestor(root->left, p, q); 15 | else if (p->val > root->val && root->val < q->val) 16 | return lowestCommonAncestor(root->right, p, q); 17 | else 18 | return root; 19 | } 20 | }; -------------------------------------------------------------------------------- /Tree/Easy/501.Find Mode in Binary Search Tree/Find Mode in Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector findMode(TreeNode* root) { 13 | if (!root) return {}; 14 | vector res; 15 | TreeNode *now = root, *pre = NULL; 16 | stack s; 17 | int mx = 0, cnt = 1; 18 | while (!s.empty() || now) { 19 | while (now) { //中序遍历,左中右。将每个结点的左子树入栈 20 | s.push(now); 21 | now = now->left; 22 | } 23 | now = s.top(); s.pop(); //取栈顶元素 24 | if (pre) { //判断当前元素和上一个元素值是否一样,一样cnt计数加一 25 | cnt = (now->val == pre->val) ? cnt + 1 : 1; 26 | } //如果cnt大于等于mx,说明当前元素重复次数大于之前最大的重复元素的次数,需要将新结果入结果栈。 27 | if (cnt >= mx) { 28 | if (cnt > mx) res.clear(); 29 | res.push_back(now->val); 30 | mx = cnt; 31 | } 32 | if (!pre) pre = new TreeNode(now->val); 33 | pre->val = now->val; 34 | now = now->right; 35 | } 36 | return res; 37 | } 38 | }; -------------------------------------------------------------------------------- /Tree/Easy/501.Find Mode in Binary Search Tree/Find Mode in Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def findMode(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: List[int] 13 | """ 14 | res = [] 15 | s = [] 16 | now = root 17 | pre = None 18 | mx, cnt = 0, 1 19 | while s or now: 20 | while now: 21 | s.append(now) 22 | now = now.left 23 | now = s.pop(len(s) - 1) 24 | if pre: 25 | if now.val == pre.val: 26 | cnt = cnt + 1 27 | else: 28 | cnt = 1 29 | if cnt >= mx: 30 | if cnt > mx: 31 | del res[:] 32 | res.append(now.val) 33 | mx = cnt 34 | if not pre: 35 | pre = TreeNode(now.val) 36 | pre.val = now.val 37 | now = now.right 38 | return res -------------------------------------------------------------------------------- /Tree/Easy/543.Diameter of Binary Tree/Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int ans; 13 | int diameterOfBinaryTree(TreeNode* root) { 14 | ans = 0; 15 | depth(root); 16 | return ans; 17 | } 18 | 19 | int depth(TreeNode *node) { 20 | if (!node) { 21 | return 0; 22 | } 23 | int left = depth(node->left); 24 | int right = depth(node->right); 25 | ans = max(ans, left + right); 26 | return 1 + max(left, right); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Tree/Easy/543.Diameter of Binary Tree/Diameter of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def diameterOfBinaryTree(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | self.ans = 0 15 | def depth(node): 16 | if not node: return 0 17 | left, right = depth(node.left), depth(node.right) 18 | self.ans = max(self.ans, left + right) 19 | return 1 + max(left, right) 20 | depth(root) 21 | return self.ans 22 | -------------------------------------------------------------------------------- /Tree/Easy/606.Construct String from Binary Tree/Construct String from Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | string tree2str(TreeNode* t) { 13 | if (!t) 14 | return ""; 15 | if (!t->left && !t->right) 16 | return to_string(t->val) + ""; 17 | if (!t->right) 18 | return to_string(t->val) + "(" + tree2str(t->left) + ")"; 19 | return to_string(t->val) + "(" + tree2str(t->left) + ")(" + tree2str(t->right) + ")"; 20 | } 21 | }; -------------------------------------------------------------------------------- /Tree/Easy/606.Construct String from Binary Tree/Construct String from Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def tree2str(self, t): 10 | """ 11 | :type t: TreeNode 12 | :rtype: str 13 | """ 14 | if not t: 15 | return '' 16 | if not t.left and not t.right: 17 | return str(t.val) + '' 18 | if not t.right: 19 | return '{}({})'.format(t.val, self.tree2str(t.left)) 20 | return '{}({})({})'.format(t.val, self.tree2str(t.left), self.tree2str(t.right)) -------------------------------------------------------------------------------- /Tree/Medium/113.Path Sum II/Path Sum II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def pathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: List[List[int]] 14 | """ 15 | if not root: 16 | return [] 17 | res = [] 18 | self.find(root, sum, [], res) 19 | return res 20 | 21 | def find(self, root, sum, ls, res): 22 | if not root.left and not root.right and root.val == sum: 23 | ls.append(root.val) 24 | res.append(ls) 25 | if root.left: 26 | self.find(root.left, sum - root.val, ls + [root.val], res) 27 | if root.right: 28 | self.find(root.right, sum - root.val, ls + [root.val], res) 29 | 30 | 31 | 32 | 33 | --------------------------------------------------------------------------------