如何找到字符串中最长的回文?


33

挑战:

创建一个在字符串中找到最长回文的函数。

注意:这是一个询问问题。请不要认真对待问题和/或答案。更多信息在这里


7
如果您不知道,这是另一个拖钓问题,尽管解释不如前一个。
Joe Z.

19
可悲的是,“一串”根本没有回文。
马克·里德 Mark Reed)2013年

17
所以,code-trolling是我的新宠标签。

4
现在,在“热门网络问题”列表中,有两个代码询问问题!
乔·Z。

18
嗯 虽然第一个[代码拖曳]问题很有趣,但我不禁感到,如果你们不小心,这些问题确实会降低本网站的质量。这些问题很容易回答,很难回答,我可以看到它们很快变得非常老旧。只是我的2美分。
里德

Answers:


19

Go中的以下解决方案利用并发,闭包和递归的隐藏功能来查找给定字符串中最长的回文式:

func lp(s string) string {
    for i, l := 0, len(s); i < l; i++ {
        if s[i] != s[l-i-1] {
            a, b := make(chan string), make(chan string)
            go func() {
                a <- lp(s[:l-1])
            }()
            go func() {
                b <- lp(s[1:])
            }()
            c, d := <-a, <-b
            if len(c) > len(d) {
                return c
            }
            return d
        }

    }
    return s
}

此外,它完全依赖于语言原语和内置类型-无需标准库-这就是您识别真正优质软件的方式。

您可能希望将线程,内存和堆栈大小的限制增加一些,以适应较大的输入字符串–这是因为此解决方案是如此之快,以至于您的OS都会对此感到嫉妒。

编辑–津贴:

  • 在多字节字符串上完全没有用。
  • 不会省略标点符号或空格字符。
  • 忽略大小写相等。
  • 很难计算时间-但是非常慢。
  • 根据输入,产生大量的goroutines。
  • 在我的计算机上运行几秒钟后,由于内存耗尽而被杀死,并生成了超过16000个 2049186 goroutine作为输入"345345ABCDEabcde edcbaDEABC12312123"

45

蟒蛇

def longest_palindrome(s):
    return 'racecar'

用法示例:

>>> print longest_palindrome('I like racecars!')
racecar

注意:这仅适用于某些字符串。


21
我用“ abcdedcba”尝试了一下,但是它刚返回了“ racecar” ...我在做什么错?
Joe Z.

22
@JoeZ。您使用了错误的字符串。试试“ abcde racecar”。
grc

10
好的,但是现在我正在尝试使用“ abcde racecar edcba”,即使回文的范围更大,它仍然只返回“ racecar”。
Joe Z.

63
@JoeZ。嗯...可能是unicode问题。
grc

11
@JoeZ。您可能应该购买一台新计算机。
emory 2013年

13

显然,检查回文检查很难。

因此,解决方案非常简单-生成与您正在测试的字符串一样大的每个可能的回文集,然后查看您的字符串是否包含该回文。

C#

string largest = String.Empty;

    for(int i=0; i < myString.lenght; i++)
    {

//Don't use the newfangled stringbuilder. Strings are awesome
char[] testString = new char[i];

    for (int charPosition=0; charPosition < i/2; charPosition++)
    {
    for (char c = 'A'; c <= 'Z'; c++)
    {
       if ((charPosition/i) == i/2)
{
//middle one
testString[i] = c;
} 
else 
{
//do one for that position, and the lenght-position
testString[i] = c;
testString[testString.length - i] = c;
}

if (myString.Contains(testString.ToString())
{
//yaay
largest = testString.ToString();
}


{

}
    } 

}


}

(我可能需要检查我的代码的正确性,但否则,这是一种检查回文率的极差的效率低下方法)


他们显然永远不会在长字符串上运行程序,因为它们很难计算。所以这很好。如果在企业环境中运行,则可以通过在更好的VPS或数据中心上运行它来扩展它。对于家庭作业,只需要3-4个字符串就可以了。
EmilVikström2014年

12

佩尔

是否一切都要求。实际上更好,因为它考虑了每个可能的子序列。有什么收获?它以指数时间运行,因此字符串中的每个附加字符都会使运行时间加倍。给它超过20个字符,这将需要一整天。

$inputstring = <>;
@arrayofcharacters = split("",$inputstring);
for(0..2**length($inputstring)-1){
 $currentsubsequence = "";
 @choice=split("",sprintf("%b",$_));
 for(0..$#arrayofcharacters){
  $currentsubsequence .= "$arrayofcharacters[$_]" x $choice[$_];
  if($currentsubsequence eq reverse($currentsubsequence)){
   $palindromes{length($currentsubsequence)} = $currentsubsequence;
   $palindromes[~~@palindromes] = length($currentsubsequence);
  }
 }
}
print($palindromes{@{[sort(@palindromes)]}[$#palindromes]})

输入:iybutrvubiuynug。输出:ibutubi

输入:abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba。输出:不会发生


从字面上看,这是我的答案,但是在Perl中。另外,不是Monekmized。编辑:nvm,我的效率更高

我将答案发布在您的答案之前,因此不会复制。
PhiNotPi

2
我首先想到了!我花了更长的时间来编写它(不得不考虑C和猴子的笑话。而且,优化值得额外的开发时间)

6
没关系。我为自己的效率低下感到自豪。
PhiNotPi

10

就像下面的图片一样,您的问题可以通过正则表达式轻松解决(但我决定改用Java)。发生这种情况是因为正则表达式始终是可用于涉及提取或分析文本的任何事物的最佳工具。

I know regular expression

package palindrome;

import java.util.regex.Pattern;
import javax.swing.JOptionPane;

public class RegexPalindrome {

    private static String next(String now) {
        if (now.isEmpty()) return "a";
        String prefix =  now.length() == 1 ? "" : now.substring(0, now.length() - 1);
        if (now.endsWith("z")) return next(prefix) + "a";
        return prefix + String.valueOf((char) (now.charAt(now.length() - 1) + 1));
    }

    public static void main(String[] args) {
        String text = JOptionPane.showInputDialog(null, "Type some text:");

        String bestPalindromeFound = "";

        for (String searchText = "a"; searchText.length() <= (text.length() + 1) / 2; searchText = next(searchText)) {
            String reverse = new StringBuilder(searchText).reverse().toString();
            if (searchText.length() * 2 - 1 > bestPalindromeFound.length()) {
                Pattern p = Pattern.compile(".*" + searchText + reverse.substring(1) + ".*");
                if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse.substring(1);
            }
            if (searchText.length() * 2 > bestPalindromeFound.length()) {
                Pattern p = Pattern.compile(".*" + searchText + reverse + ".*");
                if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse;
            }
        }
        JOptionPane.showMessageDialog(null, "The longest palindrome is \"" + bestPalindromeFound + "\".");
    }
}

该代码是邪恶的,因为:

  • 它以指数时间运行到给定文本的大小。它通过枚举az形式的所有字符串,为每个生成的字符串创建两个正则表达式并针对每个正则表达式测试输入来运行。
  • 此外,如果回文包含大写字母,数字,非ASCII文本,标点符号等,它将失败。
  • 当然,正则表达式显然不是正确的工具。

当然,GUI部件只是分散注意力:>
EmilVikström2014年

@EmilVikström是的,代码拖曳的副作用是我们可以愉快地颠覆MVC模式。此外,一个懒惰的OP可能不知道MVC是什么,并且将所有GUI耦合到其中并认为它比那些旧的提示/控制台/ DOS风格的乏味更美观,更高级的程序会给人留下深刻的印象。窗户(但他的老师可能不这么认为)。OTOH,如果懒惰的OP不喜欢耦合的GUI,那很好,那就是无论如何都要让他沮丧。
Victor Stafusa 2014年

甚至前奏是不正确的。从技术上讲,回文不属于正则语法类别,因此不能由正则表达式识别。幸运的是,我们拥有PCRE,其中包括上下文相关语法类别。
recursion.ninja 2014年

7

蟒蛇

这将字符串,并将其重组为可能的最长回文。

例如:

输入:你好

欧普特:哈哈

def get_palindrome(string):
    if len(string) == 0:
        return "I didn't catch that"
    list_of_characters = []
    occurances = []
    for character in string:
        if not character in list_of_characters:
            list_of_characters.append(character)
            occurances.append(1)
        else :
            occurances[list_of_characters.index(character)] +=1
    #check if a palindrome is possible
    if sum(occurances) == len(occurances): #no double letters, so only a one character palindrome
        return list_of_characters[0]
    first_half = ''
    second_half = ''
    middle_character = ''
    for index, character in enumerate(list_of_characters):
        number_of_occurances = occurances[index]/2
        first_half += character * number_of_occurances
        second_half = (character * number_of_occurances)+ second_half
        if (occurances[index]%2 != 0):#if there are an odd number, there will be one spare,
            #so put it in the middle
            middle_character = character
    return first_half + middle_character + second_half


print(get_palindrome(raw_input("String containing palindrome:")))

3
XD实际上很厚脸皮
肖恩·阿雷德

7

生物信息学解释

很酷的问题伙计!

不能完全清楚地指定普通语言的回文,例如是否允许使用空格。因此,尚不清楚是否应将其作为回文症:

  • 鹅看见上帝了吗?
  • 一个人,一个计划,一条运河-巴拿马!

无论如何,我认为您指的是回文式的更好的科学含义:要使核苷酸序列被视为回文式,其互补链必须在相反的方向上读相同。两条链,即从5'到3'的链以及从3'到5'的互补链都必须互补(请参见此处)。

有一些研究的回文序列识别做,我想你应该至少读。要解决您的问题,您几乎可以复制他们的方法!如果您问教授,教授甚至会发出源代码。

好吧,现在解决手头的问题。假设您有一个以字符串形式给出的核苷酸序列。在这样的序列中找到回文序列的最佳方法是使用标准算法。我认为您最好的选择可能是使用此在线工具:http : //www.alagu-molbio.net/palin.html

由于需要提供执行此任务的功能,因此您需要考虑如何将字符串放入此应用程序?好了,有趣的地方开始了。我认为您可以使用。由于我不想做功课,所以我只给你基本的想法。在Java中,您的世界是这样开始的:

package testing;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;

public class PalindromeService {


    public static void main(String[] args) {
        WebDriver d1 = new PhantomJSDriver();

        d1.get("http://www.alagu-molbio.net/palin.html");

        String sequence = "AAGTCTCGCGAGATCTCGCGAGATCTCGCGAGATCTCGCGAGAAA";

        WebElement txtArea = d1.findElement(By.tagName("textarea"));

        txtArea.sendKeys(sequence);

        WebElement send = d1.findElement(By.cssSelector("input[type=submit]"));
        send.click();

        String result = d1.findElement(By.tagName("body")).getText();

        Pattern p = Pattern.compile(".*capitalized\\.[^agctACGT]*([agctACGT]+).*");
        Matcher m = p.matcher(result);
        if (m.find()){
            result = m.group(1);
        }

        //now you have all palindromes in upper case! 
        //I think you can take it from here, right?

        System.out.println(result);

        d1.quit();
    }
}

如果您对语言回文感兴趣,可以将相同的技术与其他网络服务(例如http://www.jimsabo.com/palindrome.htmlhttp://calculator.tutorvista.com/math/492/palindrome-checker)一起使用.html

密码拖曳技术


6

蟒蛇

def get_substrings(a_string):
    """Get all possible substrings, including single character substrings"""
    for start_index in range(len(a_string)):
        for end_index in range(start_index + 1, len(a_string) + 1):
            yield a_string[start_index:end_index]

def get_longest_palindrome(a_string):
    """Find the longest palindrome in a string and return its index or -1"""

    # Initialise variables
    longest_palindrome = get_longest_palindrome.__doc__[5:27]
    palindromes_list = []

    # Search string for all palindromes
    for substring in get_substrings(a_string):
        if reversed(substring) == substring:
            palindromes_list.append(substring)

    # There should always be palindromes in non-empty strings (single characters),
    # but it's good practice to check anyway
    if len(palindromes_list) > 0:
        longest_palindrome = max(palindromes_list, key=len)

    return a_string.find(longest_palindrome)

从文档字符串中提取字符串“最长回文” longest_palindrome

reversed()函数返回一个迭代器,因此reversed(substring) == substring永远不会为真,longest_palindrome也不会被覆盖。

因此,该函数将在字面上找到字符串中的“最长回文”。


但是“最长回文”甚至都不是回文……而且其他人已经发布了这个回文。
Joe Z.

4
这些解决方案的问题在于它们太明显了。即使是初学者,程序员也知道您正在带领他们前进。
Joe Z.

1
@JoeZ。我添加了一个不太明显的版本。
grc

1
您不太明显的版本达到了目标。不过,如果删除了明显的版本,那将是很好的。
Joe Z.

5

Java脚本

哦,那很容易;)。你去:

function () {
    var palidrome = "Star? Not I! Movie – it too has a star in or a cameo who wore mask – cast are livewires.

Soda-pop straws are sold, as part-encased a hot tin, I saw it in mad dog I met. Is dog rosy? Tie-dye booths in rocks.

All ewes lessen ill. I see sheep in Syria? He, not I, deep in Syria, has done. No one radio drew old one.

Many moths – I fondle his; no lemons are sold. Loot delis, yob, moths in a deli bundle his tin. Pins to net a ball I won – pins burst input. I loot to get a looter a spot paler. Arm a damsel – doom a dam. Not a base camera was in a frost, first on knees on top spot. Now a camera was a widened dam.

Ask: Cold, do we dye? No, hot – push tap, set on to hosepipe. Nuts in a pod liven.

A chasm regrets a motto of a fine veto of wars. Too bad – I all won. A sadist sent cadets – a war reign a hero derides. A bad loser, a seer, tossed a cradle – he begat to cosset – a minaret for Carole, Beryl, Nora. We’re not as poor to self.

I risk cold as main is tidal. As not one to delay burden, I don’t set it on “hot”. A foot made free pie race losses runnier. As draw won pull, eye won nose. Vile hero saw order it was in – even a moron saw it – no, witnessed it: Llama drops – ark riots. Evil P.M. in a sorer opus enacts all laws but worst arose. Grab a nosey llama – nil lesser good, same nicer omen.

In pins? No, it is open. If a top spins, dip in soot.

Madam, as I desire, dictates: Pull aside, damsels, I set a rag not for a state bastion. A test I won e.g. a contest I won.

Kidnap, in part, an idle hero. Megastars, red, rosy, tied no tie. Blast! A hero! We do risk a yeti’s opposition!

He too has a wee bagel still up to here held.

Demigods pack no mask, cap nor a bonnet, for at last a case is open – I left a tip – it wets. A dog wets too. Radios to help pay my tip, pull a tip.

Ale, zoo beer, frets yon animal. Can it? New sex arose but, we sots, not to panic – it’s ale – did I barrel? Did I lose diadem, rare carrot in a jar of mine? Droop as tops sag – unseen knots.

A cat ate straw as buck risk cud; evil foe, nil a red nag ate? Bah! Plan it – silage. Model foot in arboreta.

I, dark Satanist, set fire – voodoo – to slat. I design a metal as parrot, I deem it now. One vast sum is no ten in set – amen! Indeed, nine drag a yam, nine drag a tie. Dame nabs flower; can we help man? Woman is worse nob.

Mud level rose, so refill a rut. A nag of iron I made to trot I defied – I risk leg and its ulnae. Can a pen I felt to bid dollar or recite open a crate, open a cradle, his garret?

Sample hot Edam in a pan. I’m a rotten digger – often garden I plan, I agreed; All agreed? Aye, bore ensign; I’d a veto – I did lose us site. Wool to hem us? No, cotton. Site pen in acacias or petals a last angel bee frets in.

I met a gorilla (simian); a mate got top snug Noel fire-lit role. Manet, Pagnol, both girdle his reed bogs.

Flan I reviled, a vet nods to order it, Bob, and assign it. Totem users go help mates pull as eye meets eye. Son – mine – pots a free pie, yes? No. Left a tip? Order a dish to get. A ring is worn – it is gold. Log no Latin in a monsignor, wet or wise. Many a menu to note carrot.

Cat in a boot loots; As I live, do not tell! A bare pussy, as flat on fire, I know loots guns, fires a baton, nets a hero my ale drop made too lax.

If it is to rain, a man is a sign; I wore macs, no melons rot. I use moths if rats relive, sir, or retire.

Vendor pays: I admire vendee, his pots net roe. Nine dames order an opal fan; I’ll ask cold log fire vendor to log igloo frost. Under Flat Six exist no devils.

Marxist nods to Lenin. To Lenin I say: “Mama is a deb, besides a bad dosser.”

Gen it up to get “ova” for “egg”. I recall a tarot code: yell at a dessert side-dish sale. Yes/nos a task cartel put correlate: E.S.P. rocks a man. I am a man, am no cad, I’m aware where it’s at!

Fire! Its an ogre-god to help, man, as I go. Do not swap; draw, pull a troll!

It’s not a cat I milk – calf, for a fee, sews a button – knit or tie damsel over us. Mined gold lode I fill until red nudes I met in a moor-top bar can. I sit, I fill a diary – trap nine men in ten-part net – oh, sir, I ask, cod nose? No, damp eel.

So, to get a name! I say, Al! I am Al! Last, I felt, to breed, deer begat.

To can I tie tissue – damp – or deliver Omani artist – a man of Islam.

In a den mad dogs lived on minis a signor who lived afore targets in at. As eremites pull, I, we, surf, fantasise, mend a bad eye. No hero met satyr; Tony, as I stressed, won’t, so cosset satyr.

A vet on isles made us sign it, a name. Foe man one sub.

Aside no dell I fret a wallaby; metal ferrets yodel, like so. On a wall I ate rye. Bored? No, was I rapt! One more calf? O.K., calf, one more, bossy! No! Lock cabin, rob yam, sip martini. Megastar was in a risk.

Cat? No, I’m a dog; I’m a sad loyal pet. A design I wore – kilts (a clan); if net drawn, I put it up. Royal spots snag – royal prevents rift.

Composer, good diet, are both super, God – label it a love of art, lustre. Video bored, no wise tale e.g. a mini tale – no sagas seen. Knack: cede no foes a canal.

Pay – as I sign I lie; clear sin it is; e.g. “Amadeus” sign I – lira for ecu, decimal – sin as liar.

Trad artistes pull a doom, a drawer won’t.

Is it sold loot? No, I suffered loss. A man is god; Amen! I came nice Tahiti (sic).

It’s ale for a ban if for a fast – is role to help mash turnip? Use zoo? No – grasp order – use no zoos. Warts on time did sag.

No grade “X” “A” Level? Oh, “A”! I’d a “B” or a “C”. So – pot? No, we lop. Date? Take no date! Bah! Play L.P.

Miss (a lass, all right?) flew to space in NASA era. Rose no (zero) cadets ate raw. As a wise tart I fined rags red Lenin, we help pay bet – a risk – cash to Brian. I put a clam in a pool – a pool wets.

Mahdi puts a stop to harem – miss it in one vote, lost in one, veto of none. Post-op, no tonsil; I ate; no tastier, eh? We sleep at noon time so I dare not at one; no time stops as I time tides. A bed: under it, roll; in a mania, panic!

In a pond I did as Eros as Lee felt tenrec. “Ink” – list it under “I”. Termites put pen in a way. Democrats wonder, I too. To slay moths a dog did.

I saw elf; elf, far now, is a devilish taboo, rag-naked. I hid a bootleg disc. I, saboteur, toss it in. Oops! No legs! Laminated, a cask, conker in it, negates all if it is simple.

Hot pages are in a mag, nor will I peer, familiar tat, so lewd, native rot. Toner, ewe wore no trace; vagabond ewes do. Oh, Ada! Have pity! A pitiable eel – “Oh wet am I!” – to save, note: bite gill as I do.

Call a matador minor, eh? As I live, don’t! Is torero no rigid animal debaser if tipsy? Ale drew esteem in a matador. A bolero, monks I rate play or go dig rocks; a can I step on.

Go! Gas – it evades a bedsit – set a roost on fire. Boss sent a faded eclair to green imp or dog, I’d don a belt to boot it; if Ada hid a boot, panic.

I mock comic in a mask, comedian is a wit if for eventide. Vole no emu loved is not a ferret, so pet or witness a weasel if not. I hired less, am not so bossy, as yet amateur.

To stir evil, Edna can impugn a hotel: bad loos, hot on Elba: I may melt. Tart solicits it rawer, gets it rare. Push crate open; I ram buses, use no trams.

Did I say, not to idiot nor a bare ferret, to trap rat, strap loops rat? Stewpot was on. Hot? I was red! Lessen it! Fine man on pot? No, pen inside by a bad law. So I made rips – nine delays.

Some Roman items in a.m. ordered “Is room for a ban?” “It is,” I voted: I sat pews in aisle. Beryl, no tiro to my burden, made off for a contest, I won kiss. I may raid fine dales. I raid lochs if I to help am.

Forecast for Clare v. Essex: If no rain, a man is ref. Fusspots net foxes.

Senor is a gnome, latinos’ bad eyesore. Help misses run to border, Casanova, now, or drab hotel.

Ma has a heron; I sleep, pet’s on nose, sir! Rev. I rag loved art live – fine poser. Ultra-plan: I feign, I lie: cedar to disperse – last one? No, last six. Enamel bonnet for a dark car to toss a snail at. In it all, Eve lost; Seth’s a hero slain on a trap – Rise, Sir Ogre Tamer.

Upon Siamese box I draw design. I, knight able to help, missed an alp seen in Tangier of fine metal pots. Tin I mined rages – order nine, melt ten. Tone radios; tones are not to concur. Ten-tone radar I bomb – best fire-lit so hostel side meets eerie mini red domicile. A gulf to get is not a rare tale; no time to nod.

Row on, evil yobs, tug, pull. If dogs drowse, fill a rut. An era’s drawers draw. Put in mid-field in a band I dig a tub deep. Staff on a remit did refill a minaret.

Sam’s a name held in a flat, or, sir, bedsit. I wonder, is it illicit ore? No ties? A bit under? Retarded? Is ‘owt amiss? I’m on pot; not so Cecil, a posh guy a hero met. A red date was not to last so Cecil sat.

Tip? An iota to pay, a dot; sad, I drop item. I’d ask, call, Odin, a Norseman’s god: “Pay payee we owe radio dosh o.n.o.” I to me? No, I to media.

Peril in golf – is ball a “fore”? K.O.!

Vexed I am re my raw desires. Alto has eye on nose but tone-muser pianist is level-eyed. I lost a tie. Blast! In uni no grades are musts. Avast! Never port! Sea may be rut.

Part on rose? – It’s a petal. Define metal:

Tin is . (I gulp!) can!

I am a fine posse man, I pull a ton. Ron, a man I put on, I made suffer of evil emu’s sadism. Leo’s never a baron – a bad loss but evil – topple him, Leo’s lad. Assign a pen, can I? A pal is note decoding.

Is damp mule tail-less? No, ill; I breed for its tone. Radio speed, to grower, grew. Open a lot? No, stamp it; if for a free peso – not ecu -deign it. Times ago stone rates, e.g. at Scilly, display a wont.

No wish to get a design I, Sir Des, I’ve let? No bus sees Xmas fir. O.K. – cab – tart it up; tie lots – diamond, log or tinsel; first end errata edit. So “le vin (A.C.)”, Martini, Pils lager, one tonic.

I pegged a ball up to here when I got a top star role, Beryl. Gun is too big – won’t I menace? Yes? No?

Ill? A cold? Abet icecap’s nip. U.S.A. meets E.E.C. inside tacit sale – see! Beg a cotton tie, ma! No trial, so dodo traps exist. Arabs under-admire card label good hood stole.

In rage erupted Etna. Will a rotunda, bare villa, to tyro. Lack car? Non-U! Get a mini! My, my, Ella, more drums per gong; get a frog – nil less. Rod, never ever sneer. Got to?

I disperse last pair of devils (ah!) here today or else order cash to breed emus. Said I: “Are both superlative?” C.I.D. assign it lemon peel still. I wore halo of one bottle from a ref (football) – a tip; so hit last ego slap a mate got.

Late p.m. I saw gnu here (non-a.m.) or an idea got a dog to nod – I made felt to boot.

Fill in a lad? Nay, not all, Edna – lash to buoy. Did you biff one Venus? Not I! “Broth, girl!” ladies ordered – “No, with gin!” – a fine plate, maybe suet; no carton I made rots in it.

Med: a hill, Etna, clears in it. Ali, Emir, to slap in/slam in. All in all I made bad losers sign it – alibi. Set a lap for a level bat.

A bed, sir, eh? To put cat now? Drat! Such an idyll of a dog’s lair! That`s it, open it – a cage! Big nit sent rat! Some day (A.D.) send ewe. No, draw a pot now, do! Of wary rat in a six ton tub.

Edna, ask satyr: “Tel. a.m.?” No, tel. p.m.; Israeli tuner is damp. Use item: “Anna Regina”. No! Dye main room (“salle”) red!

Nice caps for a sea cadet in U.S.A. – Now I, space cadet, am it, sea vessel rep. Pin it on Maria, help Maria fondle her fine hotpot. No! Meet; set up to net, avoid a lesion. Set acid arena: Bruno one, Reg nil. Like it to sign in? Even I am nine-toed! I vote votes.

Oh, can a nose-rut annoy? No, best is Dorset. I know, as liar, to snoop, malign. “I’ll order it to get a bedroom door,” began a miser I fed.

Am I to peer, fan? Is a door by metal? Ere sun-up, drowse, nod, lose magnet. Food? Buns? I’ll ask. Corn? I’ll ask. Corn – I snack. Cats snack (cold rat). Sum for a bag: nil. First, is remit “traps in net”? Yes, on a par. Coots yell over a dam I made. Bared nudist went a foot, I made roots. I tip a canon: “Row, sir, at same tide; man one: row tug.”

Sewer of denim axes a wide tail – a terror recipe to hero made manic. I, to resign? I ? Never!

“OFT I FELT ITS SENSUOUSNESS” – title fit for evening is erotic; I named a more hot epic – error retaliated – I was examined for ewe’s gut, wore no named item.

A star is worn on a cap, it is too red. Am I too fat? Newts I’d under a bed. Am I mad? Are volleys too crap? A nosey tennis part-timer sits rifling a bar of mustard.

Lock cans, stack cans in rocks, all in rocks, all I snub. Do often games, old ones, word-pun use; relate, my brood, as in a free pot I made fires, I manage brood. Moor debate got tired rolling, I lampoon, so trail saw on kites.

Rod sits, ebony on nature, so Nana chose to veto video. Ten in main evening is O.T.T. i.e. killing; Ere noon, urban eradicates noise, lad, I ovate not. Put esteem on top (to hen, if reheld).

No fair ample hair – am not I nipper-less? Eva estimated ace caps I won as united. A Caesar of space, Cinderella’s moor, Niamey Don (a Niger-an name), ties up mad sire, nut! I, Lear, simpleton male, try tasks “A” and “E”

but not “XI”. Sanitary raw food won top award one Wednesday – a demo.

Start nesting, I beg a cat. I? Nepotist? Ah, trials, God! A folly, Dinah, custard won’t act up; other is debatable. Velar: of palate; sibilating is “s”.

Resold: a bed, a mill, an ill animal – snip, also trim. Eilat in Israel can tell I had ‘em. Tin I stored (am I not raconteuse?) by a metal pen. If a night, I wondered, rose, I’d all right orbit on sun, even off.

I buoy, did you? Both Sal and Ella, Tony and Alan (“Ill if too bottle-fed, am I?”) do not. God! A toga! Ed in a Roman one, rehung! Was I, M.P. et al., to get a map? Also get salt? I, hospital lab to offer, am, or felt to be, no fool – a hero.

Will it sleep? No, melting is sad ice. Vital re-push to be raid, I assume. Deer, both sacred roes, Leroy (a doter, eh?) has lived for. I, apt sales rep’s idiot to greens, revere vendors selling or fat egg-nog reps.

Murder O’Malley, my mini mate – gun on rack. Calory total: liver, a bad nut or all I wanted (“et puree garnie”): lots. “Do, oh do, ogle bald racer,” I’m dared – N.U.S. bar at six.

Esparto, dodo’s lair to name it, not to cage bees, elasticated, is nice. Esteem, as up in space, cite bad local lions, eye can emit now. G.I. boots in ugly rebel or rat’s potato gin (eh?) were hot. Pull a bad egg – epic, I note, no regal slip in it. Ram can . (I’ve lost idea!)

Tarred nets, rifles, nitro, gold – no maid stole it. Put it, rat, back or if Sam (“X”) sees sub on televised rising, I sedate Goths. I won’t – no way.

Alps, idyllic stage set, are not so gas-emitting, I educe. To nose, peer, far off, I tip mats onto lane. Power grew or got deep so I dare not stir. Of deer, billions sell. I ate lump – mad sign, I do cede – tonsil a pain, acne pang is sad also. Elm I help pot, live – tub’s sold; a ban or a bar, even so, elms, I’d assume, live for. Effused am I not, up in a manor, not all up in a mess.

Open if a main A.C. plug is in it.

Late men I fed late – pasties or not. “Rapture” by a maestro prevents a vast sum erased.

Argon in units, albeit at solid eye level, sits in a . (I presume not) . tube, son. No eyes: a hot laser – is Ed wary?

Mermaid, ex- evoker of all A.B.s, I flog. Nil I repaid. Emotion! Emotion, oh so do I dare, woe!

Wee yap-yap dog’s name’s Ron. An idol lacks a dime tip, or did, as today a potato in a pitta slice costs a lot – tons. A wet adder ate more hay. Ugh! So, pal, ice cost on top? No, miss, I’m a two-sided rat, erred nut, I base it on erotic ill; It is I, red now; it is debris, rot.

Alf, an idle he-man as “master animal lifer” did time, ran off at speed, but a G.I. did nab an idle if dim nit. Upwards rewards are natural life’s words, God. Fill up guts, boy, live now or do not emit one later. A rat on site got flu.

Gaelic, I’m odd Erin, I’m Eire, esteemed islet. So hostile rifts ebb. Mob, I.R.A., dare not net R.U.C. – no cotton. Erase not, so I dare not nettle men in red rose garden – I’m in it.

Stop late men if foreign at nine. Esplanades, simple hotel, bath, gin – king is Edward IX; obese; Ma is no pure mater. Go! Rise, sir; part anon.

I also rehash tests – ‘O’ Level Latin, Italian. S.A.S., so, to track radar. Often nobleman exists alone – not sales reps – I do. Trade ceiling, i.e. final part, lures open if evil trade.

Volga River rises on no steppe. Elsinore has a hamlet – Oh, Bard, row on Avon!

A sacred robot nurses simple hero’s eye; dabs on it a lemon. Gas, iron, Essex often stops, suffers in a mania. Ron fixes several crofts, acer of maple. Hot, I fish; cold, I arise laden; if diary amiss, I know it set no car off. Foe-damned ruby motor, it only rebels.

Ian I swept aside to visit, in a bar of moorside red, Romanis met in a more mossy ale den. Inspired am I, Oswald. A bay bed is nine p on top. No name, niftiness- elder saw it. Oh no! Saw top wet star’s pool – part star, part otter. Refer a baron to idiot, Tony, as I did.

Smart ones use submarine.

Poet, arch-super-artiste, grew artistic. I lost rattle; my amiable, not oh so old, able to hang up, mina, can deliver it, so true. “Ta, matey!” – says so Boston (Mass.) elder I hit.

On file S.A.E. was sent – I wrote poster re fat on side, volume one – loved it, never off it, I was in. Aide mocks a manic; I mock comic, I nap: too bad I had a fit, I too. Bottle ban odd, I go drop mine, ergo trial ceded a fatness, sober if not so, or a test is debased.

A vet is agog – no pet’s in a cask – corgi dog, royal pet, a risk no more.

Lob a rod at a man I meet. Sewer delays pit fires – a bedlam in a dig – iron ore rots it. No devil is a hero – Nimrod.

At a mall a cod is all I get. I bet on Eva, so Tim ate whole eel bait, I pay tip, Eva had a hood sewed. No B.A. gave car to Nero, we were not to rev it and we lost a trail; I’m a free pill, I wrong a man. I erase gap; to help miss it, I fill a set. A gent in ire knocks a cadet.

Animals’ gel on spoon – it is so true to basics – I’d gel; too bad I hide kangaroo baths – I lived as I won raffle, flew as I did go, dash, to my, also too tired now, star comedy: A wan, inept, upset I’m retired, nut; its ilk, nicer. Nettle feels a sore; sad, I did no panic in a pain, am an ill or tired, nude, based item; it is a spot.

Semitone, not a tone, radios emit; no, on tape; elsewhere it’s a tone.

Tail is not on; pots open on foot, even on it, so let oven (on, it is) simmer – a hotpot’s a stupid ham stew.

Loop a loop, animal – cat up in air.

Both sacks I rate by apple hewn in elder’s garden if it rates, I was aware – tasted a core.

Zones or areas, Annie, cap, so twelfth girl, lass, alas, simply (alpha beta) done, Kate. Tadpole won top Oscar, Obadiah, “O” Level axed.

Argon gas did emit no straw, so ozone sure drops argon, oozes up in Ruth’s ample hotel or sits afar off in a bar – of elastic, is it?

I hate cinema; cinema dogs in a mass. Older effusion to old – lost, is it now? Reward: a mood.

All upsets it.

Radar trails an Islamic educer of a riling issue, damages it in Israel. Ceiling is, I say, a plan, a case of one deck. Can knees sag as one Latin image elates, I wonder?

Oboe diverts ultra foe, volatile bald ogre – push to berate; I’d do, ogre. So, p.m., Oct. first, never play organ’s stops – lay or put it up in ward ten.

Final cast like rowing – I sedate play, old as am I, God! Am I! On tacks I ran; I saw rats. A Gemini tramp is May born.

I back colony’s sober omen of lack of lace. Rome, not Paris, a wonder.

Obey retail law – a noose killed oyster. Reflate my ball, a water-filled one. Disabuse no name of emanating issue.

Damsels, I note, vary tastes so cost now desserts. I say no! Try taste more honeyed. A bad nemesis at naff ruse will upset. I, mere Satanist, e.g. rater of a devil – (Oh wrong is a sin!) – I’m no devil’s god, damned.

Animals, if on a mat, sit. Rain, a more vile drop, made us site it in a cottage. Breed deer – bottle fits a llama.

I lay, as I emanate, go to sleep, mad ones on docks – air is hot. Entrap, net, nine men in party raid – all if it is in a crab-pot room, an itemised, under-lit, nullified old log den – I’m sure voles made it rot in knot.

Tubas we see far off lack limit. A cat on still or tall upward paws to no dog is an ample hot-dog, ergo nastier if tastier, eh? We, raw amid a conman, a mama in a mask, corpse et al., err.

Octuple tracks at a son’s eyelash side distressed a tall eye doctor, a tall ace, rigger of a vote: got put in egress; odd, abased, is ebbed, as I am, Amy, asinine lot! Nine lots! Don’t six rams live? Don’t six exist?

Alfred, nuts or fool gigolo, trod never if gold locks all in a flap on a red rose; made nine or ten stops.

I heed never, I’m Daisy, a prod never, I terrorise viler starfish. To me suitors, no lemons, came rowing. Is a sin a mania? Rot!

Sit! I fix a looted amp or delay more, hasten not. A baser if snug stool, wonkier, if not – Alf says – super, a ballet to no devil, is a stool too. Ban it, actor, race to no tune.

May names I wrote wrong (Is no man in it, a long old log?) sit in row, sign irate Goths; I dare drop it. At felon’s eye I peer, fast open – I’m nosey, esteem eyes. All upset, ample hogs resume totting. Is sad nabob tired? Roots don’t evade liver in Alf’s gob.

Deers I held right; oblong, apt enamel or tile rifle on gun spot to get a man – aim is all. I rogate, minister. Feeble gnats, alas late, prosaic, a canine pet is not to consume hot.

Loo, wet, issues old idiot; evading, I sneer, obey a deer, gall a deer, gain alpine dragnet for egg I’d net to ram in a pan I made to help master. Rags I held, arcane poet, arcane poetic error, all odd; I bottle fine panacean lust. I’d nag elks I ride if editor toted a minor. I fog a natural life.

Roses, or level dumb ones – rows in a mown, ample, hewn acre. Wolfsbane made it a garden in May, a garden indeed.

Nine mates, nine tons I must save now on time – editor raps a late man. G.I.s edit also, too. Do over if tests in a task radiate. Rob ran; I, too, fled.

“Omega” – list in alphabet.

A gander, a line of live ducks, irk cubs. A wart, set at a cast on knee, snug as spots.

A poor denim for a janitor, racer, armed aide, solid idler – rabid; I’d elastic in a pot, tons to sew.

Tubes or axes went in a clam, in an oyster. Free booze – lap it all up. Pity, my apple hot, so I’d a root stew. God, a stew! Tip it at feline! Posies, a cat’s altar often, no baron packs. A monk caps dog – I meddle here – hot? Pull its leg! A bee was a hoot, eh?

No, it is opposite. Yaks I rode wore hats, albeit on deity’s orders. Rats age more held in a trap, nip and I know it – set no cage now.

It’s eta; no, it’s a beta – Tsar of Tonga rates isles. Mad Ed is all upset at cider, is Ed? Is a madam too? Snip? I’d snip, spot a fine position, snip nine more cinemas.

Do ogres sell in a mall? Yes, on a barge so rats row tubs.

Wall last canes up or Eros, an imp, lives to irk, rasp or dam all tides sent. I won’t – I was no Roman – even I saw tired row – a sore. He lives on. “No!” we yell.

Up, now! Wards are in nurses’ sole care. I, peer, fed, am too fat? Oh, not I, test no dined ruby ale; dote not on salad it’s in – I am sad.

Locks I rifle so troops atone re war. Only rebel or a crofter animates so cottage beheld arcades, so trees are sold, abased. I redo, rehang, I err – a wasted act; nests I’d – as an owl – laid. A boot’s raw foot, even if a foot to master, germs (ah!) can evil do.

Pan is tune-pipe – so hot notes, paths up to honeydew.

Odd locks, a maddened (I was aware) macaw on top, spot no seen knots, rifts or fan, I saw. Are maces a baton, madam? Oodles, madam? Rare laptops are too late – got too lit up.

Nits rub – snip now, I’ll abate, not snip, nits I held.

Nubile Danish tomboys I led to old loser as no melons I held; no fish to my name. Nod lower, do I dare? No, one nods a hairy snipe. (Edit: one hairy snipe, eh?) See silliness, else we’ll ask cornish to obey deity’s or god’s item. I, God, damn it! I was in it! To Hades, acne trap, sad loser! As warts pop, a dosser I – we – vile rat, sack! Same row, oh woe! Macaroni, rats, as a hoot, tie. I vomit on rats.";
return '$system> KERNEL ERROR (DOES. NOT. EXCIST)'
}

:)


那击败了这个吗?
Joe Z.

1
@JoeZ。它实际上是这样做的;)我的单词数为24,122!
C1D

2
太棒了!先生,您赢得了2个网际网路和5个金属雪貂
yodel

4

Ruby-(优化和猴子化!)蛮力

我发现最好的方法是通过众所周知的猴子算法,您可能可以在BOOST中找到它。他们总是有办法让你说话。

def palindrome?(in)#IMPORTANT
  if in.reverse == in
    return true
  else
    return false
end

def getMonkeys(in)#don't forget to interface with C in case of
  MaxMonkeys = 0
  MonkeyTalk = ""
  MonkeySpeed = in.length
  (0..MonkeySpeed).each do |monkeyA|
    (monkeyA..MonkeySpeed).each do |monkeyB|#optimized!
      if palindrome?(in[monkeyA..monkeyB]) do
        if in[monkeyA..monkeyB].length > MaxMonkeys do
          MonkeyTalk = in[monkeyA..monkeyB]
        end
      end
    end
  end
  MonkeyTalk
end

如果将所有内容重命名为其原始名称,则效率极低,但非常可爱且类似于红宝石:MaxMonkeys = len; MonkeyTalk =结果,MonkeySpeed = strlen; monkeyA:一个;monkeyB:b; getMonkeys:getMaxPalindrome。
这对OP没有任何价值,并且冒着他决定与C进行实际交互的风险,我们都知道结局如何……


4

Python 2.7

我拒绝使用标准功能,因为它们效率低下。每个人都知道查找长度的最佳方法是要有一个表供参考,因此我创建了所有可能的回文表,并使用pythonic bogosort对它们进行排序,但是为了提高效率,我首先删除了重复项。到那时,我计算了所有回文项目,并按长度对它们进行了排序。然后,您可以简单地获取列表中的最后一个长度,该长度可以通过迭代列表进行O(n)查找。

码:

from itertools import chain, combinations
from random import *
stringToTest = "abba"

#Don't forget to reference code taken from stackoverflow. (http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list)
def FindAllSubsetsOfAString(StringToFindASubsetOf):
  return chain(*map(lambda x: combinations(StringToFindASubsetOf, x), range(0, len(StringToFindASubsetOf)+1)))

listOfPermutations = []

#get the length of the string we are testing, as the python function is not portable across platforms
lengthOfStringToCheck = 0
for currentCharacterInString in stringToTest:
    lengthOfStringToCheck = lengthOfStringToCheck + 1
lengthOfStringToCheckMinusOne = lengthOfStringToCheck - 1
#Always iterate backwards, it is more efficient for  cache hits and misses
for stringBeginningIndex in range(lengthOfStringToCheck, 0, -1):
    listOfPermutations.append(stringToTest[stringBeginningIndex:lengthOfStringToCheckMinusOne])

#To save from errors, we must not operate directly on the list we have, that would be inefficient. We must copy the original list manually.
# The built in functions again aren't portable, so we must do this manually, with a deep copy.
OtherListOfPermutations = []
for CurrentItemInOriginalList in listOfPermutations:
    TemporaryListItem = []
    for CurrentIndexInCurrentItemInOriginalList in CurrentItemInOriginalList:
        TemporaryListItem.append(CurrentIndexInCurrentItemInOriginalList)
    OtherListOfPermutations.append(''.join(TemporaryListItem))

#Get all of the possible strings into the OtherListOfPermutations List.
# Use Generators, and itertools. It's more efficient and more pythonic
for OriginalString in listOfPermutations:
    for CurrentPermutationInCurrentString in FindAllSubsetsOfAString(OriginalString):
      OtherListOfPermutations.append(''.join(list(CurrentPermutationInCurrentString)))

#Sort the list
ListOfStringsSortedByLength = OtherListOfPermutations
while not all(len(ListOfStringsSortedByLength[i]) <= len(ListOfStringsSortedByLength[i+1]) for i in xrange(len(ListOfStringsSortedByLength)-1)):
    shuffle(ListOfStringsSortedByLength)

#Remove all of the duplicates in the sorted list
ListOfStringsSortedByLengthWithoutDuplicates = []
for CurrentStringWorkingWith in OtherListOfPermutations:
    HaveFoundStringInList = False
    for CurrentTemporaryString in OtherListOfPermutations:
        if CurrentStringWorkingWith == CurrentTemporaryString:
            HaveFoundStringInList = True
            if(HaveFoundStringInList == True):
                ListOfStringsSortedByLengthWithoutDuplicates.append(CurrentStringWorkingWith)

#Use the ListOfStringsSortedByLengthWithoutDuplicates and check if any of the strings are palindromes
ListOfPotentialPalindromes = []
for TemporaryStringToUseForPalindromes in ListOfStringsSortedByLengthWithoutDuplicates:
    lengthOfStringToCheck = 0
    for currentCharacterInString in TemporaryStringToUseForPalindromes:
        lengthOfStringToCheck = lengthOfStringToCheck + 1
    if lengthOfStringToCheck != 0:
        TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1]
        if TemporaryStringToUseForPalindromesReversed == TemporaryStringToUseForPalindromes:
            ListOfPotentialPalindromes.append(TemporaryStringToUseForPalindromes)

#Remove any duplicates that might have snuck in there
ListOfPotentialPalindromesWithoutDuplicates = []
for CurrentPotentialPalindrome in ListOfPotentialPalindromes:
    HaveFoundStringInList = False
    for CurrentTemporaryPalindrome in ListOfPotentialPalindromes:
        if CurrentPotentialPalindrome == CurrentTemporaryPalindrome:
            HaveFoundStringInList = True
            if(HaveFoundStringInList == True):
                ListOfPotentialPalindromesWithoutDuplicates.append(CurrentStringWorkingWith)

lengthOfPalindromes = []

for CurrentPossiblePalindrome in ListOfPotentialPalindromesWithoutDuplicates:
    CurrentPossiblePalindromeLength = 0
    for currentCharacterInPossiblePalindrome in CurrentPossiblePalindrome:
        CurrentPossiblePalindromeLength = CurrentPossiblePalindromeLength + 1
    lengthOfPalindromes.append(CurrentPossiblePalindromeLength)


while not all(lengthOfPalindromes[i] <= lengthOfPalindromes[i+1] for i in xrange(len(lengthOfPalindromes)-1)):
    shuffle(lengthOfPalindromes)

#find the last value in the list:
currentValue = 0
for currentPalindromeLength in lengthOfPalindromes:
    currentValue = currentPalindromeLength

print currentValue

注意

不适用于长度超过4个字符的字符串。“ abba”没问题,但是我去买咖啡和煮熟的午餐后才去做abcba

问题:

疯狂的变量命名(也不一致)
荒谬的算法选择(计算给定字符串的每个子字符串的所有可能排列,检查它们是否是回文,按长度排序并查找最后一个值)
实际上包含问题的解决方案

    TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1] 

愚蠢的排序算法(bogosort)和确保列表被排序的nutjob方法。

另外,重复检查中有一个缩进错误,实际上根本不执行任何操作,这只是浪费时间。


4

C

查找回文是PNP *的一项艰巨任务,因此必须使用高度优化的代码来完成。这里有五个优化技巧,可以帮助您更快地找到解决方案。

  1. 从正确的语言开始。众所周知,“ C”是最快的。
  2. 使用快速算法。 BoyerMoore是字符串搜索的世界纪录保持者,因此我们将使用它。我们还将首先搜索最长的子字符串,因此我们有最大的机会找到长匹配项。
  3. 了解您的处理器。现代计算机在if this else that表格的各个分支处的运行速度非常慢。(随着您事业的发展,如果您想成为真正的代码忍者,则应该掌握分支预测。)该代码if通过使用for语句来避免分支问题,该语句以3个价格的价格提供了3条指令。
  4. 注意“ Big-O”。该算法在函数体内不使用花括号,从而防止了任何嵌套循环。因此,运行时必须为O(N)。
  5. 不要忘记微优化。通过使用众所周知的删除所有语句间空白的技术,我能够减少编译器的工作量并获得10%的加速。

但是请不要忽略变量名,可读性很重要。

*回文不是回文

#define OFFSET 0XFF
#define ln(s) strlen(s) //macro to avoid runtime overhead

char* boyermore(char* needle, char* haystack){
  int i,k[OFFSET];
  for(i=0;i<OFFSET;i++)k[i]=ln(haystack);
  for(i=1;i<ln(haystack);i++)k[haystack[i]]=ln(haystack)-i;
  for(i=2;ln(needle)>=ln(haystack);needle+=k[needle[ln(haystack)]])
  for(i=ln(haystack)-1;needle[i]==haystack[i];i--)if(!i)return needle;
  return 0xFF-OFFSET;
}

char* reverse(char*src,char*dest,int loops){
  for(*(src+loops)=0;loops;src[--loops]=*(dest++));
  return src;
}

#define imax(a,b) ((a>b)?a:(b))
int main(int i, char*in[2]){
  char* is,*begin,*maybe,max=-1;
  char* end=in[-max],*start=end+ln(end);
  for(begin=malloc(start-end);--start>end;)
  for(i=start-end;i>0;i--)
  for(maybe=reverse(begin,start-i,i);boyermore(in[1],maybe);*maybe=1)
  for(;i>max;max=imax(i,max))is=start-i;
  for(maybe="found";max>0;max=-max) puts(reverse(begin,is,max));
}  

除了评论中明显的巨魔外,还有其他一些问题。搜索算法是Boyer-Moore-Horspool的有效实现,但是它从不存储字符串长度,而是调用strlen之类的N * M次,这比简单的搜索要慢得多。“首先搜索最长的字符串”是正确的,但此后它不会按长度顺序搜索,因此,如果实施,则提前退出会给出错误的答案。但是不是,因此它搜索所有N!反正可能性。几乎所有参数名称(needle / haystack; src / dest)都与它们的标准含义相反。


3

这是我到目前为止在VB6中所拥有的:

Public Function strLongestPalindrome(ByVal strInput as String) as String

    strLongestPalindrome = ""
    Dim a as Integer
    Dim b as Integer

    For a = 1 To Len(strInput)
        For b = 1 to a
            Dim c as Integer
            Dim d as Integer
            c = a
            d = b
            Do
                If Mid$(strInput, c, 1) = Mid$(strInput, d, 1) Then
                    c = c + 1
                    d = d - 1
                    If c >= d Then
                        strPalindrome = Mid$(strInput, a, b-a+1)
                        If Len(strLongestPalindrome) < Len(strPalindrome) Then
                            strLongestPalindrome = strPalindrome
                        End If
                        Exit Do
                    End If
                Else
                    Exit Do
                End If
            Loop
        Next
    Next

End Function

但是我认为它行不通,而且我认为可以做得更好。


2
尽管对于以前从未在VB6中进行过编码的人来说,这应该是最后一个非拖尾的答案,但您可能不知道它不应该拖拉。
Joe Z.

3

这是为您提供的Java解决方案:

public String findLongestPalindrome(String s){
   if(s.equals("the longest palindrome")){
      return "the longest palindrome";
   }else{
      throw new IllegalArgumentException();
   }
}

3
但是“最长回文”甚至都不是回文……
Joe Z.

2

自动热键

;msgbox % longest_palindrome_in_string("racecar abcdedcba alkdf")

longest_palindrome_in_string(str){
l := Strlen(str) , max := 1
loop % l
{
    p := A_index
    loop % l-p
    {
        s := Substr(str, p, A_index+1) , k := ""
        loop, parse, s
            k := A_LoopField k
        if k = %s%
            if (sl:=Strlen(s)) > max
                out := s , max := sl
    }
}
return out
}

该函数也返回空格,因为它们是字符串中回文序列的一部分。所以上面的回报<space>abcdedcba<space>


1

多种语言

这是拖钓,因为它要求“在字符串中找到最长回文”,因此它正在找到“字符串”中最长的回文

String palindrome(){
    return null; //There are no palindromes in "a string"
}

当我将“ abcba”放入其中时,此操作不会返回任何内容...确定会起作用吗?
Joe Z.

@JoeZ。我忘了说为什么会拖钓了
scrblnrd3

5
我了解这一点,但是正如我告诉其他很多人一样,这太明显了。这种文字游戏不会造就一个好巨魔。
Joe Z.

1
“字符串”中有多个回文(一个字符长)。上面的代码不正确。

2
@Ben在“字符串”-“”,“ a”,“”,“ s”,“ t”,“ r”,“ i”,“ n”,“ g”中有9个回文。这个问题显然要求最长(如单数)回文。正如我所看到的那样,这里有8条平局,答案是不确定的。因此null为适当的返回值。
emory


1

遍历字符串的每个字符。然后检查该字符之前和之后的字符。然后是该字符的前两个字符和后两个字符。不断重复直到找到不相同的字符。这将使您能够识别单词中每个回文的长度。但是,此方法仅适用于奇数长度的回文。要检查均匀长度的回文,请检查位置i和i-1,i + 1和i-2,i + 2和i-3等的字符,希望对您有所帮助!


1

显而易见的答案是将字符串与其自身的逆进行比较,并计算最长的公共序列。

下面的Perl程序就是这样做的。您可能需要下载Acme :: DonMartin模块,默认情况下通常不安装该模块。

use Acme::DonMartin;

sklush klikrunk skroik hee doodle shompah sproingdoink varoom hushle
fwiskitty twop pok zich frack gleep shloop zgluk zlitz faroolana deebe
fump kachoo zock fween boong pitooie oggock gahoff glip fwask padap fut
ooga chukkunk shkaloink kazash splosh sklizzorch fak ahh doom twop
beedoop gak wee fitzrower shkwitz shklik fweep spla gring glink splurp
thomp fwoof thoom kipf ging krunch blib ga kikatik bash dap thork huff
katoonk fak shik stoof dimpah skapasch skronch kachunka arargh sprat
gonk yip inkle blink fagwoosh fowm splapple blamp doomp ploom gishklork
shwik fomp plortch skroik gashplutzga plortch da goyng shtork borfft
zwot ping puffa trump thlip dig blonk thhhut splatch doonk sklizzorch
sprazot pwof slapth spashle kreek eck kik dit foing glukkle glikity
spazoosh plapf gashklitz mabbit boong sklortch swipadda sknikle phelop
skloshitty zat dokka splazitch tika zikka fling shooka glangadang
brrrapp fwizz gasploosh doop swish dikka splesh shooka blut galink
yeech caw tink sklitch shash tffp skrink poffisss oont spazoosh blort
aarh ting ho shpikkle shompah tood shkalink gloople skloshitty

您可以在此处找到该模块:metacpan.org/pod/Acme
dland

1

Lua / Python

Lua是一种非常快速的语言(您需要使用它,因为要检查很多子字符串!),但是Python在字符串处理方面更好。那么为什么不同时使用它们呢?

因为我听说有局部变量很好,所以我有一个。另外,我将函数调用与它们的参数分开,因为太多的参数使表达式混乱且难以理解。

另外,我认为这可以与您想要尝试的任何字符串一起使用,奇怪的输入可能不会有任何问题。

function is_palindrome()
    if os.execute("python -c 'exit(\"" .. is_palindrome_argument .. "\"==\"" .. is_palindrome_argument .. "\"[::-1])'") == true then
        return false
    else
        return true
    end
end

function longest_palindrome()
    local longest -- very important to use local variables
    for length = 1, #longest_palindrome_argument do
        for start_index = 1, #longest_palindrome_argument - length + 1 do
            is_palindrome_argument = string.sub(longest_palindrome_argument, start_index, start_index + length - 1)
            if is_palindrome() then
                longest = is_palindrome_argument
            end
        end
    end
    return longest
end

longest_palindrome_argument = "foo racecar"
print(longest_palindrome())

(顺便说一句,您不会相信我花了多长时间才能使它正常工作。)


1

Python一线式:

s = "here goes your string"
print max(p for p in [s.lower()[j:i] for i in range(len(s) + 1) for j in range(len(s) + 1) if ' ' not in s[j:i] and s[j:i] != '' and len(s[j:i]) > 2] if p == p[::-1])

1

Python-126个字符

这是我的努力:

k=[]
for i in range(len(p)):
 for j in range(i,len(p)):
  if p[i:j]==p[j:i:-1]:
   k.append(p[i:j+1])
k.sort(key=len)
k=k[-1]

我相信,这在Python 2.x和3.x中均适用。变量k保留答案。

编辑:我忘了说,变量p应该保存字符串以检查回文。

这是一个合法的实现,因此适用于任何字符串。


顺便说一句,这是我第一次打高尔夫球!hoo!:P
cjfaure

它实际上具有一个代码拖曳标签,因此是一个代码拖曳竞赛。
皮埃尔·阿洛德

1
@ArlaudPierre Yup,在我发布后意识到了这一点。叹。xD
cjfaure 2014年

我的意思是说是一场人气*竞赛。好的,没关系xD
Pierre Arlaud 2014年

0

爪哇

显然,如果aString本身就是回文,那么它aString就是里面最长的回文aString。您可以通过断言声明它正在运行。不要对可执行代码的第一行考虑太多。那只是标准的java样板。

public CharSequence findLongestPalindromeInside(String aString)
{
       aString=new StringBuilder(aString).append(new StringBuilder(aString).reverse());
       assert isPalindrome(aString);
       return aString;
}

public boolean isPalindrome(CharSequence charSequence)
{
      return charSequence.toString().equals(new StringBuilder(charSequence).reverse().toString());
}

0

游戏制作者语言

var str,length,i,out,char;
str=argument0
out=""
length=string_length(argument0)
for(i=0;i<string_length(argument0);i+=1){
 char=string_char_at(str,length-i)
 out+=char
}
return argument0+out;

可能想描述发生了什么事?
Joe Z.

0

Fortran

字符串太难使用,无法在Fortran中使用,因此我选择iachar了将其全部转换为整数的方法:

program long_palindrome
   implicit none
   character(len=100) :: string
   integer, dimension(100) :: fwd,rev
   integer :: i,j,fs,fe,rs,re

   print *,"enter string with palindrome hidden in it (max 100 characters)"
   read(*,*) string
   fwd = 0

! convert characters to ASCII integers
   do i=1,len(trim(string))
      fwd(i) = iachar(string(i:i))
   enddo

! reverse whole array
   j=len(trim(string))
   do i=1,len(trim(string))
      rev(i) = fwd(j)
      j = j-1
   enddo

! match strings of fwd and rev
   rs = 1; re = len(trim(string))
   fs = 1; fe = len(trim(string))

! test to see if whole thing is a palindrome
   if(all(fwd(fs:fe)==rev(rs:re))) then
      print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1
      stop
   endif

! nope? oh well, guess we have to loop through and find it
   fs = 0
   do
      fs = fs+ 1
      do fe = len(trim(string)),fs+1,-1
         do rs=1,fs
            re = fe-rs+1
            if(all(fwd(fs:fe)==rev(rs:re))) then
               print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1
               stop
            endif
         enddo
      enddo
      if(fs==len(trim(string))-1) exit
   enddo

   print *,"hmm, doesn't look like there was a palindrome of length > 1..."
end program long_palindrome

它不完全起作用。给定字符串aabbaac表示最长aa,但是给定字符串acasdabbbaabb表示最长abbba。足够近。


实际上,bbaabb第二个要更长。
Joe Z.

@JoeZ .:就像我说的那样,足够接近。:D
Kyle Kanos

0

您只能按照要求做,不能在当今市场上竞争。该代码还将找到最短的回文,并且不区分大小写:

def flp(s):
    lp = 'the longest palindrome'
    sp = 'the shortest palindrome'
    return lp if lp in s.lower() else sp if sp in s.lower() else ''

>>> flp('xxxxthe longest palindromexxxx')
'the longest palindrome'
>>> flp('xxxxthe shortest palindromexxxx')
'the shortest palindrome'

0

a

function findPalendromes(str)
    str=str.." "
    ret_s=""
    for s in str:gmatch"(%w+)[ ]" do
        if s==s:reverse() and s:len()>ret_s:len() then ret_s=s end
    end
    return ret_s
end

0

最有效的Python实现胜过其他所有努力:

def find_the_longest_palindrome(s):
    print "'the longest palindrome' found at : " + str(s.find("the longest palindrome"))

笔记:

这样总会发现“最长回文”

区分大小写。

经过一些修改,也可以找到其他字符串。但是,您将需要创建一个类,添加适当的方法,然后为要找到的每个字符串将其子类化。

可以通过移植到FORTRAN 77或将其硬编码为Intel 8008机器代码来改进此功能。


0

这是我的第一个代码拖曳答案。这不是一个特别残酷的巨魔,它以一种愚蠢的方式回答了我

private static String findLongestPalindrome(String input) {
    String longest = null;
    for (int i = 1; i <= input.length(); i++) {
        Matcher m = pattern(i).matcher(input);
        if (m.find()) {
            longest = m.group();
        }
    }
    return longest;
}

private static Pattern pattern(int len) {
    int size = len / 2;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        sb.append("(.)");
    }

    if (len != size * 2) {
        sb.append(".");
    }

    for (int i = size; i > 0; i--) {
        sb.append("\\").append(i);
    }
    return Pattern.compile(sb.toString());
}

巨魔是:

  • 每次手动创建相同的图案
  • 使用昂贵的反向引用查找回文
  • 从1迭代到input.length()(以相反的方式进行操作,可以确保找到的第一个匹配项最长。以上述方式进行的操作是愚蠢的)

0

Python 3

from itertools import takewhile

def common_part(s1, s2):
    return sum(takewhile(bool, (a==b for a, b in zip(s1, s2)))) 

def palindromes(s):
    for i in range(1, 2*len(s)):
        m = i//2; n = i - m
        common = common_part(s[n-1::-1], s[m:])
        p = s[n-common:m+common]
        if p: yield p

string = input('> ')

print('Longest palindrome is', repr(max(palindromes(string), key=len)))

非常高效的程序。它以中心位置在连续位置(在char和之间)搜索长回文,并选择最长的

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.