Leetcode 409 Longest Palindrome

栏目: 编程工具 · 发布时间: 7年前

内容简介:本题是给定一个字符串,求可以用其中字符组成的最长回文长度。Link:思路:

本题是给定一个字符串,求可以用其中字符组成的最长回文长度。

Link: https://leetcode.com/problems/longest-palindrome/

思路:

1,暴力破解,挨个枚举,时间复杂度O(n!)

2, 用hashtable记录每个字符出现的次数,成对出现(2的倍数)即视为可组成回文,最终落单的+1放中间,时间复杂度O(n)

比如:’abccccdd’

a: 1
b: 1
c: 4
d: 2

最终转换成

a: 1
b: 1
c: 0
d: 0

代码:

function getCounts(s) {
	const hashtable = {};
    let char = null;
	for (let idx = 0; idx < s.length; idx++) {
		char = s[idx];
		if (hashtable[char]) {
			hashtable[char]++;
		} else {
			hashtable[char] = 1;
		}
	}
	return hashtable;
}

var longestPalindrome = function(s) {
	const table = getCounts(s);
	let left = 0;
	let count = 0;
	for (const key in table) {
		const item = table[key];
		count += Math.floor(item / 2);
		table[key] = item % 2;
		left += table[key];
	}

	if (left > 0) {
		return count * 2 + 1;
	} else {
		return count * 2;
	}
};

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Art and Science of Java

The Art and Science of Java

Eric Roberts / Addison-Wesley / 2007-3-1 / USD 121.60

In The Art and Science of Java, Stanford professor and well-known leader in CS Education Eric Roberts emphasizes the student-friendly exposition that led to the success of The Art and Science of C. By......一起来看看 《The Art and Science of Java》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具