409. Longest Palindrome

LeetCode easy original: C# #csharp #easy #hash-table #leetcode #string
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

Если задана chaîne s, состоящая из строчных или прописных букв, return длину самого длинного палиндрома, который можно построить из этих букв. Буквы чувствительны к регистру, наExemple, "Aa" не считается палиндромом.

Exemple:

Input: s = "abccccdd"

Output: 7

C# solution

correspondant/original
using 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

brouillon automatique, à relire avant soumission
#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

correspondant/original
import 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

correspondant/original
function 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

correspondant/original
def 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

correspondant/original
package 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

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.