Find Words That Can Be Formed by Characters - Leetcode 1160 - Python

Поділитися
Вставка
  • Опубліковано 9 лис 2024

КОМЕНТАРІ • 8

  • @1vader
    @1vader 11 місяців тому +3

    Minimal Python solution using Counter's built-in comparison operators:
    def countCharacters(self, words: List[str], chars: str) -> int:
    chars = Counter(chars)
    return sum(len(word) for word in words if Counter(word)

  • @rebellious_703
    @rebellious_703 11 місяців тому +1

    Easy and medium Leetcodes give confidence. Generally, none-faang companies ask such questions. Thanks for the efforts.

  • @ajitsdeshpande
    @ajitsdeshpande 7 місяців тому +1

    @NeetcodeIO: In the example on Leetcode where chars= "atach", how can cat and hat be good, because then we are using letter t twice, which is not allowed. So result should have been 3 (not 6)

    • @alibasyari6535
      @alibasyari6535 11 днів тому

      it cannot use the letter t or any other letter more than the availability of the letter on the chars (e: hatch doesn't count because there's only 1 h in atach, which missing one more letter h), but can be used for more than one words, like the example: cat and hat

  • @Abazigal100
    @Abazigal100 11 місяців тому +4

    Do you solve Advent of Code problems too? What's your opinion on the difficulty of their problems? Like are they comparable to Leetcode ones

    • @1vader
      @1vader 11 місяців тому +1

      It varies by day and year. Generally, the first few days are pretty easy, roughly like Leetcode Easys, but later days get much harder. Probably mostly around Leetcode Mediums but some of the harder ones are similar to Leetcode Hards. But it's not a strictly linear increase, the hardest problems are spread around towards the end with some easier ones in between. But each year is a bit different.

  • @yang5843
    @yang5843 11 місяців тому

    Java solution
    class Solution {
    public int countCharacters(String[] words, String chars) {
    Map map = new HashMap();
    for (char c : chars.toCharArray())
    map.put(c,map.getOrDefault(c,0)+1);
    int rc =0 ;
    for ( String w : words) {
    Map used = new HashMap();
    boolean good = true;
    for ( char c : w.toCharArray())
    {
    if ( !map.containsKey(c) || used.getOrDefault(c,0)+1 > map.get(c) ) {
    good = false;
    break;
    }
    used.put(c,used.getOrDefault(c,0)+1);
    }
    if ( good )
    rc += w.length();
    }

    return rc;
    }
    }

  • @yang5843
    @yang5843 11 місяців тому

    Ah, I misinterpreted this question. It seemed too easy. I thought it asked to output total length of the combination of words that formed String chars.