409. Longest Palindrome

LeetCode easy original: C# #csharp #easy #hash-table #leetcode #string
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

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

Beispiel:

Input: s = "abccccdd"

Output: 7

C# Lösung

zugeordnet/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++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 к длине палиндрома для центрального символа.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.