题目:
思想:
当不存在t里所有元素的时候,右指针右移
当存在t里所有元素的时候,左指针右移,如果右指针没有到最右边,继续移动右指针
如果找到t,跳出返回
优化:
The code finds the minimum length window in string s that contains all the characters in string t. The code uses two pointers, left and right, to traverse s and keep track of the window. The isAll function checks if the characters in t are present in the current window.
To improve the code, consider the following:
Use a dict dict_keys instead of the isAll function to track the count of each character in the current window, and update the count directly instead of using Counter function repeatedly.
Remove unused variables ans, hash_1, and dict_t.
Initialize right outside the loop, and use while right < len(s) and not isAll(dict_keys, dict_t) as the loop condition to terminate when all characters in t are present in the current window.
Keep track of the minimum window length and the start and end indices of the window, and return s[start:end + 1] at the end.
get()方法语法:
dict.get(key[, value])
参数
key -- 字典中要查找的键。
value -- 可选,如果指定键的值不存在时,返回该默认值。
返回值
返回指定键的值,如果键不在字典中返回默认值 None 或者设置的默认值。
实例
以下实例展示了 get() 函数的使用方法:
实例
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tinydict = {'Name': 'Runoob', 'Age': 27}
print ("Age : %s" % tinydict.get('Age'))
# 没有设置 Sex,也没有设置默认的值,输出 None
print ("Sex : %s" % tinydict.get('Sex'))
# 没有设置 Salary,输出默认的值 0.0
print ('Salary: %s' % tinydict.get('Salary', 0.0))
代码:
1 | class Solution: |
1 | class Solution: |