thảo luận Leetcode mỗi ngày

  • Người tạo chủ đề Người tạo chủ đề _Gia_Cat_Luong_
  • Ngày bắt đầu Ngày bắt đầu
Trạng thái
Không mở để trả lời thêm.
Dễ lại ngoi lên :smile:

C++:
    int longestPalindrome(string s) {
        int ret = 0, carry = 0;
        unordered_map<char, int> map;
        for(auto c : s) map[c]++;
        for(auto [c, n] : map) {
            int is_odd = (n % 2);
            ret += (n - is_odd);
            if (is_odd) carry = 1;
        }
        return ret + carry;
    }
 
Sửa lần cuối:
:D
Java:
class Solution {
    public int longestPalindrome(String s) {
        int len = backtrack(0, 0, new HashMap<Character, Integer>(), s);

        if (len < s.length()) {
            return len + 1;
        }

        return len;
    }

    private int backtrack(int pos, int max, Map<Character, Integer> map, String s) {
        if (pos == s.length()) {
            return max;
        }

        char c = s.charAt(pos);

        map.put(c, map.getOrDefault(c, 0) + 1);

        if (map.get(c) % 2 == 0) {
            return backtrack(pos + 1, max + 2, map, s);
        } else return backtrack(pos + 1, max, map, s);
      
    }
}
Bài dễ mà bác bị nghĩ quá rồi :LOL:
 
Ờ có ai submit cái ăn luôn ko. Tôi ko :|
C#:
public class Solution
{
    public int LongestPalindrome(string s)
    {
        Dictionary<char, int> dict = new();
        for (int i = 0; i < s.Length; i++)
        {
            if (!dict.ContainsKey(s[i]))
            {
                dict.Add(s[i], 1);
                continue;
            }
            dict[s[i]]++;
        }

        int result = 0;
        int odd = 0;
        foreach (var entry in dict)
        {
            if (entry.Value % 2 == 0)
            {
                result += entry.Value;
                continue;
            }

            result += entry.Value - 1;
            odd = 1;
        }

        return result + odd;
    }
}
 
Java:
public int longestPalindrome(String s) {
    Map<Character, Integer> frequency = new HashMap<>();
    for (char ch : s.toCharArray()) {
        frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
    }

    int oddCount = 0;
    for (int count : frequency.values()) {
        if (count % 2 == 1) {
            oddCount++;
        }
    }

    return oddCount > 1 ? s.length() - oddCount + 1 : s.length();
}
 
Mã:
func longestPalindrome(s string) int {
    m := make(map[rune]int)
    for _, c := range s {
        m[c]++
    }
    var l int
    var k bool
    for _, c := range m {
        if c%2 == 0 {
            l += c
        } else {
            l += c - 1
            k = true
        }
    }
    if k {
        l++
    }
    return l
}
 
Screenshot 2024-06-04 at 09.06.29.png


Á đù, đang có 5k chuẩn bị mua mũ mà có cái này chắc quay xe thôi :big_smile:
 
Java:
public int longestPalindrome(String s) {
        char[] c = s.toCharArray();
        int res=0;
        int[] freq = new int[52];
        for(char i:c){
            if(i>='A' && i<='Z'){
               freq[i-'A'+26]++;
            }
            else{
                freq[i-'a']++;
            }
        }
        for(int i=0;i<52;i++){
            if(freq[i]%2==1){
                res++;
                break;
            }
        }
        for(int i=0;i<52;i++){
            int pair = freq[i]/2;
            res+=pair*2;
        }
        return res;
    }
 
code vội code rác quá, thôi pass là đc
JavaScript:
function longestPalindrome(s: string): number {
    const arr = new Array(58).fill(0);
    for (const c of s) arr[c.charCodeAt(0) - 'A'.charCodeAt(0)]++;
    arr.sort((a,b) => b-a);
    let ans = 0, hasOdd = false;
    for (let i = 0; i < 58; i++) {
        if (arr[i] === 0) break;
        if (arr[i] % 2 === 0) ans+= arr[i]
        else if (hasOdd) ans+= arr[i] - 1;
        else {
            ans+= arr[i];
            hasOdd = true;
        }
    }
    return ans;
};
 
JavaScript:
/**
 * @param {string} s
 * @return {number}
 */
var longestPalindrome = function (s) {
    let hasOdd = 0;
    const map = new Map();

    for (let i = 0; i < s.length; i++) {
        if (map.has(s[i])) {
            map.set(s[i], map.get(s[i]) + 1);
        } else {
            map.set(s[i], 1);
        }
    }

    let counter = 0;

    for (const [letter, times] of map) {
        if (times % 2 === 1) hasOdd = 1;

        if (times >= 2) {
            counter += times % 2 ? times - 1 : times;
        }
    }

    return counter + hasOdd;
};
 
Python:
class Solution:
    def longestPalindrome(self, s: str) -> int:
        # Approach 3: 2 lines for fun
        freq = Counter(s)
        return min(len(s), sum([freq[f] - (freq[f] % 2)  for f in freq ]) + 1)
 
Cày đến lúc 9k coin chắc cx mùa đông ròi. Hoodie hợp lí r. Mà vã quá thì làm quả áo thôi :look_down:
 
Swift:
class Solution {
    func longestPalindrome(_ s: String) -> Int {
        let dict = Dictionary(grouping: s){$0}.mapValues{$0.count}
        var result = 0
        var odd = false
        for (_, count) in dict {
            result += (count/2)*2
            odd = odd || count%2==1
        }
        return result + (odd ? 1:0)
    }
}
 
Thôi mua cái áo đã, rồi cày tiếp cái mũ + hoodie. Cày hết list của leetcode luôn là hợp lí.
 
Cày đến lúc 9k coin chắc cx mùa đông ròi. Hoodie hợp lí r. Mà vã quá thì làm quả áo thôi :look_down:
hoodie ko hợp mặc ở vịt ngan, nhất là trong miền nam đi nắng sói đầu mặc nửa năm thành màu nâu hết:sad: fen chỉ mặc chống lạnh mặc buổi tối thì ok, chứ mặc thành áo chống nắng cái áo ko thọ
 
Python:
class Solution:
    def longestPalindrome(self, s: str) -> int:
        freq = {}
        res = 0
        hasOddFreq = False
        for c in s:
            freq[c] = freq.get(c,0)+1
        for f in freq:
            if freq[f]%2==0:
                res+=freq[f]
            else:
                res+=freq[f]-1
                hasOddFreq=True
        return res+1 if hasOddFreq else res
 
A/e cố làm cái áo + hoodie, đi phỏng vấn mặc full set. Vào phòng bảo nóng quá cởi hoodie ra. Interviewer thấy chắc không giám hỏi thuật toán nữa :D
 
PHP:
class Solution {
    /**
     * @param String $s
     * @return Integer
     */
    function longestPalindrome($s) {      
        // count number appear of char in s
        $dict = [];
        for ($i=0; $i<strlen($s); $i++) {
            if (!isset($dict[$s[$i]])) {
                $dict[$s[$i]] = 1;
            } else {
                $dict[$s[$i]]++;
            }
        }

        // calculate palindrome for even count
        $palLength = 0;
        $oddSum = 0;
        $oddLenght = 0;
        foreach ($dict as $char => $count) {
            // the even chars will be palindrome
            if ($count % 2 == 0) {
                $palLength += $count;
            } else {
                $oddSum += $count;
                $oddLenght++;
            }
        }

        // all odd counts need to be decreased by 1, except 1 item to make the palindrome
        $palLength += ($oddLenght > 1) ? $oddSum - ($oddLenght-1) : $oddSum;
        return $palLength;
    }
}
 
Sửa lần cuối:
Trạng thái
Không mở để trả lời thêm.

Thống kê chủ đề

Ngày tạo
_Gia_Cat_Luong_,
Người trả lời cuối
Vipluckystar,
Trả lời
17.755
Lượt xem
1.213.912
Quay lại
Lên đầu trang