美文网首页
对称子字符串

对称子字符串

作者: loick | 来源:发表于2019-11-25 19:24 被阅读0次
Description

Given a string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.

(给定字符串,只包含数组,找出最长的子字符串,满足子字符串的长度为2k位,左k位的总和等于右k位的总和。)

思路

遍历每一个字符x, 计算以x为中心的最长的满足条件的子字符串:

  1. k从1开始,计算x左边k位和suml,与右边k位和sumr,

  2. 如果相等,检查k+1,

  3. 否则更新最长结果 ans = max(ans, 2*k)

参考实现(O(n^2))
def solve(s):
    nums = list(map(int, s))
    ans, n = 0, len(nums)
    for i in range(len(nums)-1):
        l, r = i, i+1
        suml = sumr = 0
        while l >= 0 and r < n:
            suml += nums[l]
            sumr += nums[r]
            if suml == sumr and i-l+1 > ans:
                ans = i-l+1
            l -= 1
            r += 1
    return ans*2

for _ in range(int(input())):
    s = input()
    print(solve(s))
完整代码

O_NJU_JK

相关文章

  • 对称子字符串

    Description Given a string ‘str’ of digits, find length o...

  • 对称子字符串

    问题描述 Given a string ‘str’ of digits, find length of the l...

  • 两个指针遍历

    1,有一个很常见的问题叫子字符串,相关的问题有LCS(最长公共子字符串),还有最长对称子字符串问题。我们先不讨论算...

  • 最长回文子串

    子串:小于等于原字符串长度由原字符串中任意个连续字符组成的子序列 回文:关于中间字符对称的文法,即“aba”(单...

  • 最长对称子字符串(2)

    解法一在 http://www.jianshu.com/p/d23c6b0e02e2中已经写了,这个方法复杂度太高...

  • pyton判断一个字符串是否是对称字符串

    可以先思考几分钟 判断一个字符串是否是对称字符串, 例如"abc"不是对称字符串,"aba"、"abba"、 "a...

  • L1_008最长对称子串

    对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对...

  • 输入一个字符串s,我们可以删除字符串s中的任意字符,让剩下的字符

    输入一个字符串s,我们可以删除字符串s中的任意字符,让剩下的字符串形成一个对称字符串,且该字符串为最长对称字符串。...

  • HJ85 最长回文子串

    描述给定一个仅包含小写字母的字符串,求它的最长回文子串的长度。所谓回文串,指左右对称的字符串。所谓子串,指一个字符...

  • 回文子串

    给出一个字符串,取该字符串的一部分即为子串,回文子串就是指该子串正着读,倒着读都是一样的(也就是对称的),例如:a...

网友评论

      本文标题:对称子字符串

      本文链接:https://www.haomeiwen.com/subject/ntnjwctx.html