deflongestValidParentheses3(self, s: str) -> int: max_len = self.get_max_len(s) res = [] PARENTHESES_DICT = {'(': ')', ')': '('} for char in s: res.append(PARENTHESES_DICT[char]) max_len = max(max_len, self.get_max_len(res[::-1])) return max_len
defget_max_len(self, s: str) -> int: max_len = res = left = right = 0 for char in s: if char == '(': left += 1 if char == ')': right += 1 if left < right: left = 0 right = 0 res = 0 if left == right: # (())), ()() res += left * 2 max_len = max(max_len, res) left = 0 right = 0 return max_len
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array numsafter the possible rotation and an integer target, return the index oftargetif it is innums, or-1if it is not innums.
You must write an algorithm with O(log n) runtime complexity.
1 <= nums.length <= 5000-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup> All values of nums are unique.
nums is an ascending array that is possibly rotated. * -10<sup>4</sup> <= target <= 10<sup>4</sup>
1 <= strs.length <= 10<sup>4</sup>0 <= strs[i].length <= 100 * strs[i] consists of lowercase English letters.
题目大意:
对同字母不同序单词分组
算法思路:
N/A
注意事项:
list(id_to_words.values())要转成list
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
defgroupAnagrams(self, strs: List[str]) -> List[List[str]]: id_to_words = collections.defaultdict(list) for word in strs: id_to_words[self.get_id(word)].append(word) returnlist(id_to_words.values()) # remember to convert it to list
defget_id(self, word): char_to_freq = collections.Counter(word) res = '' for c in string.ascii_lowercase: if c in char_to_freq: res += c + str(char_to_freq[c]) return res
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题目大意:
最大子数组和
算法思路:
dp[i] = max(dp[i-1] + nums[i], nums[i])
注意事项:
引入全局最大的res,因为递归式是以末位为结尾的最大和
Python代码:
1 2 3 4 5 6 7 8 9 10
# dp[i] = max(dp[i-1] + nums[i], nums[i]) defmaxSubArray(self, nums: List[int]) -> int: sum, res = -sys.maxsize, -sys.maxsize for num in nums: ifsum > 0: sum += num else: sum = num res = max(sum, res) return res