409. Longest Palindrome
Task text is translated from Russian for the selected interface language. Code is left unchanged.
Если задана string s, состоящая из строчных или прописных букв, return длину самого длинного палиндрома, который можно построить из этих букв. Буквы чувствительны к регистру, наExample, "Aa" не считается палиндромом.
Example:
Input: s = "abccccdd"
Output: 7
C# solution
matched/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++ solution
auto-draft, review before submit#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 solution
matched/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 solution
matched/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 solution
matched/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 solution
matched/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 к длине палиндрома для центрального символа.
😎
Vacancies for this task
Active vacancies with overlapping task tags are shown.
There are no active vacancies yet.