leetcode (5) Longest Palindromic Substring js代码实现

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.

Subscribe to see which companies asked this question

这个题目是要求最长子回文串

JavaScript代码实现

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
	//1.处理字符串
	var l = s.length;
	var ret = "$";
	for(var i = 0; i < l; i++){
		ret += "#" + s.substr(i, 1); 
	}
	ret += "#";
	var n = ret.length;
	//2.找到每个str[i]对应的最长子回文串,写进数组p[i]
	//回文子串边界
	var mx = 0;
	//回文子串中心位置
	var pi = 1;
	//数组,ret[i]的最长回文子串半径
	var p = new Array();
	for(var i = 0; i < n; i++){ 
		p[i] = 1;
	}
	for(var i = 1; i < n; i++){
		//j是i关于pi的对称点
		var j = 2 * i -1;
		if(mx>i)
        {
            p[i]=Math.min(mx-i,p[2*pi-i]);
        }
        else
        {
            p[i]=1;
        }
		while((ret[i - p[i]] == ret[i +p[i]]) && (i - p[i] >= 0) && (i + p[i] < n)){
			p[i]++;
		}
		if(p[i] > mx - i)
        {
            mx = p[i] + i;
            pi = i;
        }
	}
	//返回最长回文串
	var max = 0;
	var center = 0;
	for(var i = 1; i < n; i++){
		if(p[i] > max){
			max = p[i];
			center = i;
		}
	}
	ret = ret.substr(center - max + 1, 2 * max -1);
	ret = ret.split("#");
	ret = ret.join("");
	return ret;
};

注意substr方法的参数意义

你可能感兴趣的:(leetcode,JavaScript,javascript,string)