JavaScript 算法题求解——最长的回文子字符串?

https://leetcode.com/problems/longest-palindromic-substring/
GivenastringS,findthelongestpalindromicsubstringinS.Youmay
assumethatthemaximumlengthofSis1000,andthereexistsone
uniquelongestpalindromicsubstring.
输入字符串S,求字符串中最长的回文子字符串,并返回,如输入dbakokabbbbbbb返回bakokab
varlongestPalindrdome=function(s){
vart=s.split("").join("#");
varc=1,e=0,cs=0;
t="~"+t+"#";
for(varj=1,lenj=t.length-1;jwhile(t[j+c]===t[j-c]){
c++;
}
if(c>e){
e=c;
cs=j;
}
}
varresult=t.slice(cs-e+1,cs+e).replace(/#/g,"").replace(/~/g,"");
returnresult;
};
求解更快的算法,不知道200ms的算法是怎么样的?
测试用例之一:
vars='whdqcudjpisufnrtsyupwtnnbsvfptrcgvobbjglmpynebblpigaflpbezjvjgbmofejyjssdhbgghgrhzuplbeptpaecfdanhlylgusptlgobkqnulxvnwuzwauewcplnvcwowmbxxnhsdmgxtvbfgnuqdpxennqglgmspbagvmjcmzmbsuacxlqfxjggrwsnbblnnwisvmpwwhomyjylbtedzrptejjsaiqzprnadkjxeqfdpkddmbzokkegtypxaafodjdwirynzurzkjzrkufsokhcdkajwmqvhcbzcnysrbsfxhfvtodqabvbuosxtonbpmgoemcgkudandrioncjigbyizekiakmrfjvezuzddjxqyevyenuebfwugqelxwpirsoyixowcmtgosuggrkdciehktojageynqkazsqxraimeopcsjxcdtzhlbvtlvzytgblwkmbfwmggrkpioeofkrmfdgfwknrbaimhefpzckrzwdvddhdqujffwvtvfyjlimkljrsnnhudyejcrtrwvtsbkxaplchgbikscfcbhovlepdojmqybzhbiionyjxqsmquehkhzdiawfxunguhqhkxqdiiwsbuhosebxrpcstpklukjcsnnzpbylzaoyrmyjatuovmaqiwfdfwyhugbeehdzeozdrvcvghekusiahfxhlzclhbegdnvkzeoafodnqbtanfwixjzirnoaiqamjgkcapeopbzbgtxsjhqurbpbuduqjziznblrhxbydxsmtjdfeepntijqpkuwmqezkhnkwbvwgnkxmkyhlbfuwaslmjzlhocsgtoujabbexvxweigplmlewumcone';
//返回:wfdfw
莫回无
浏览 355回答 2
2回答

慕的地6264312

jsfunctionfn1(s){varret='';for(vari=0,il=s.length;i=0&&indexRightret.length){ret=tmp;}}returnret;}functionfn2(s){varstart=0,length=0;for(vari=0,il=s.length;i=0&&indexRightlength){start=indexLeft+1;length=tmpLength;}}returns.substr(start,length);}varstr='dbakokabbbbbbb';console.time('spend1');console.log(fn1(str));console.timeEnd('spend1');console.time('spend2');console.log(fn2(str));console.timeEnd('spend2');
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript