[LeetCode][JavaScript]Longest Palindromic Substring

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 };

 

 

posted @ 2015-08-29 22:19  `Liok  阅读(563)  评论(0编辑  收藏  举报