写一个函数,返回最长的回文给定的字符串中 [英] Write a function that returns the longest palindrome in a given string

查看:274
本文介绍了写一个函数,返回最长的回文给定的字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如ccddcc中的字符串abaccddccefe

e.g "ccddcc" in the string "abaccddccefe"

我想到了一个解决方案,但它为O(N ^ 2)时间

I thought of a solution but it runs in O(n^2) time

算法中1:

步骤: 它是一种强制的方法

Steps: Its a brute force method

  1. 有2环
    对于i = 1到i小于array.length -1
    对于j = i + 1的到j小于array.length
  2. 这样,您就可以得到每一个可能的组合的字符串从数组
  3. 有一个回文功能,它检查一个字符串是否是回文
  4. 让每一个子(I,J)调用这个函数,如果它是一个回文其存储在一个字符串变量
  5. 如果你发现下一个回文子串,如果是大于当前之一,目前进行更换。
  6. 在最后的字符串变量将有答案
  1. Have 2 for loops
    for i = 1 to i less than array.length -1
    for j=i+1 to j less than array.length
  2. This way you can get substring of every possible combination from the array
  3. Have a palindrome function which checks if a string is palindrome
  4. so for every substring (i,j) call this function, if it is a palindrome store it in a string variable
  5. If you find next palindrome substring and if it is greater than the current one, replace it with current one.
  6. Finally your string variable will have the answer

问题: 1.本算法中为O(N ^ 2)的时间。

Issues: 1. This algo runs in O(n^2) time.

算法中2:

  1. 反转字符串,并将其存储在diferent阵列
  2. 现在,发现无论是阵列
  3. 之间的最大匹配子
  4. 然而,这也为O(N ^ 2)时间
  1. Reverse the string and store it in diferent array
  2. Now find the largest matching substring between both the array
  3. But this too runs in O(n^2) time

你们可以认为它运行在一个更好的时间的算法中的。如果可能的话O(n)的时间

Can you guys think of an algo which runs in a better time. If possible O(n) time

推荐答案

您可以用找到的最长的回文 Manacher的算法 O(N)的时间!它的实施可以发现这里和的here
对于输入的String =HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE。它找到了正确的输出是 1234567887654321

You can find the the longest palindrome using Manacher's Algorithm in O(n) time! Its implementation can be found here and here.
For input String s = "HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE". It finds the correct output which is 1234567887654321.

这篇关于写一个函数,返回最长的回文给定的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆