409. Longest Palindrome
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.
Если задана cadena s, состоящая из строчных или прописных букв, return длину самого длинного палиндрома, который можно построить из этих букв. Буквы чувствительны к регистру, наEjemplo, "Aa" не считается палиндромом.
Ejemplo:
Input: s = "abccccdd"
Output: 7
C# solución
coincidente/originalusing System.Collections.Generic;
public class Solution {
public int LongestPalindrome(string s) {
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in s) {
if (charCount.ContainsKey(c)) {
charCount[c]++;
} else {
charCount[c] = 1;
}
}
int length = 0;
bool oddFound = false;
foreach (int count in charCount.Values) {
if (count % 2 == 0) {
length += count;
} else {
length += count - 1;
oddFound = true;
}
}
return oddFound ? length + 1 : length;
}
}
C++ solución
borrador automático, revisar antes de enviar#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int LongestPalindrome(string s) {
unordered_map<char, int> charCount = new unordered_map<char, int>();
foreach (char c in s) {
if (charCount.count(c)) {
charCount[c]++;
} else {
charCount[c] = 1;
}
}
int length = 0;
bool oddFound = false;
foreach (int count in charCount.Values) {
if (count % 2 == 0) {
length += count;
} else {
length += count - 1;
oddFound = true;
}
}
return oddFound ? length + 1 : length;
}
}
Java solución
coincidente/originalimport java.util.HashMap;
import java.util.Map;
public class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
int length = 0;
boolean oddFound = false;
for (int count : charCount.values()) {
if (count % 2 == 0) {
length += count;
} else {
length += count - 1;
oddFound = true;
}
}
return oddFound ? length + 1 : length;
}
}
JavaScript solución
coincidente/originalfunction longestPalindrome(s) {
const charCount = {};
for (const char of s) {
charCount[char] = (charCount[char] || 0) + 1;
}
let length = 0;
let oddFound = false;
for (const count of Object.values(charCount)) {
if (count % 2 === 0) {
length += count;
} else {
length += count - 1;
oddFound = true;
}
}
return oddFound ? length + 1 : length;
}
Python solución
coincidente/originaldef longestPalindrome(s):
charCount = {}
for char in s:
charCount[char] = charCount.get(char, 0) + 1
length = 0
oddFound = False
for count in charCount.values:
if count % 2 == 0:
length += count
else:
length += count - 1
oddFound = True
return length + 1 if oddFound else length
Go solución
coincidente/originalpackage main
func longestPalindrome(s string) int {
charCount := make(map[rune]int)
for _, char := range s {
charCount[char]++
}
length := 0
oddFound := false
for _, count := range charCount {
if count % 2 == 0 {
length += count
} else {
length += count - 1
oddFound = true
}
}
if oddFound {
return length + 1
}
return length
}
Algorithm
Создайте словарь для подсчета количества каждого символа в строке.
Пройдитесь по словарю и добавьте четное количество каждого символа к длине палиндрома. Если встречается нечетное количество символа, добавьте (count - 1) к длине палиндрома.
Если есть хотя бы один символ с нечетным количеством, добавьте 1 к длине палиндрома для центрального символа.
😎
Vacantes para esta tarea
Se muestran vacantes activas con etiquetas coincidentes.
Todavía no hay vacantes activas.