码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Longest Palindromic Substring

时间:2015-08-29 22:58:51      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

https://leetcode.com/problems/longest-palindromic-substring/

 

 


 

 

暴力,从头到底遍历,以当前的数为回文中心,判断是否为回文。

每一轮遍历,看看与上个数是否相同,相同就跳过。

找回文的时候,先要向右合并相同的数。

 1 /**
 2  * @param {string} s
 3  * @return {string}
 4  */
 5 var longestPalindrome = function(s) {
 6     var max = -1, res = "", count, i, j;
 7     for(var index = 0; index < s.length; index++){
 8         if(s[index - 1] && s[index] === s[index - 1]){
 9             continue;
10         }
11         count = 1;
12         i = j = index;
13         while(s[j + 1] && s[j + 1] === s[index]){
14             j++, count++;
15         }
16         while(s[i] && s[j] && s[i] === s[j]){
17             count += 2;
18             i--; j++;
19         }
20         if(count > max){
21             max = count;
22             res = s.substring(i + 1, j);
23         }
24     }
25     return res;
26 };

 

 

[LeetCode][JavaScript]Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4769939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!