首页 > 技术文章 > 最长回文串

gongyanzh 2020-03-17 16:44 原文

1160. 拼写单词

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和

示例 1:

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。

示例 2:

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
def countCharacters(words, chars) -> int:
    results = ""
    from collections import Counter
    for word in words:
        vocab = Counter(chars)#字典存储每个字符出现次数
        result = ""
        for w in word:#对每个单词,如果所有的字符都在字典中出现,且字母个数满足要求
            if w in vocab and vocab[w]>0:
                result += w
                vocab[w] -= 1 
            else:
                break
        if len(result)==len(word):
            results += result
    return len(results)
#如果词中所有字符出现过,该词满足要求
def countCharacters(words, chars) -> int:
    ans = 0
    from collections import Counter
    vocab = Counter(chars)
    for word in words:
        dic = Counter(word)
        for w in dic:
            if dic[w] > vocab[w]:
                break
        else:   #for 循环被break后,else语句就不会执行
            ans += len(word)
    return ans

5. 最长回文子串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
#暴力法,找出所有子串,判断是否为回文,记录长度
#超出时间限制
def longestPalindrome(s):
    maxlen = 0
    result = ""
    if not s:
        return ""
    if len(s)<2:
        return s
    #找子串
    for i in range(len(s)):
        for j in range(i+1):
            substr = s[j:i+1]
            #判断子串是否为回文串,是就记录长度
            sub_len = is_palindrome(substr)
            if  sub_len > maxlen:
                maxlen = sub_len
                result = substr
    return result

def is_palindrome(s):
    left,right = 0,len(s)-1
    while left<right:
        if s[left] != s[right]:
            return 0
        left += 1
        right -= 1
    return len(s)
# 中心展开
#如果子串为回文,向两侧展开,左右相等同样为回文
def longest_palindrome(s):
    start,end =0,0
    for i in range(len(s)):
        len1 = expand(s,i,i)#回文长度为奇数
        len2 = expand(s,i,i+1)#回文长度为偶数
        maxlen = max(len1,len2)
        if maxlen > end-start:
            start = i-(maxlen-1)//2
            end = i+maxlen//2
    return s[start:end+1]

def expand(s,left,right):
    L,R = left,right
    while L >=0 and R <len(s) and s[L]==s[R]:
        R += 1
        L -= 1
    return R-L-1

推荐阅读