72. Edit Distance
Difficulty 584 favorites Share switched to English concern feedback
Given two words word1 and word2 , and calculates an word1 converted word2 minimum number of operations used.
You can perform the following three operations on one word:
- Insert a character
- To delete a character
- Replace a character
Example 1:
输入: word1 = "horse", word2 = "ros"
输出: 3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
def minDistance(word1, word2) -> int:
n = len(word1)
m = len(word2)
dp = [[0] * (n2 + 1) for _ in range(n1 + 1)]
# init boundaries
for i in range(n + 1):
d[i][0] = i
for j in range(m + 1):
d[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1] ) + 1
#print(dp)
return dp[-1][-1]
409. The longest palindrome string
135 Favorite Share difficulty simply switch to English concern feedback
Given a capital letter and lowercase letter string comprising, configured to find the longest by letters palindromic sequence.
In the construction process, please note case sensitive. Example, "Aa"
not as a palindrome string.
Note:
assuming that the length of the string is not more than 1,010.
Example 1:
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
def longestPalindrome(s) -> int:
if not s:
return 0
from collections import Counter
dic = Counter(s)
ans=0
for v in dic.values():
ans += v//2*2
if ans % 2 == 0 and v % 2 == 1:#变为奇数后,ans值不会在进行加一
ans += 1
return ans