How to check if a string can be constructed by using the letters of another string in Python

2 Answers

0 votes
def can_construct(s: str, another: str) -> bool:
    freq = [0] * 256  # ASCII frequency table

    # Count characters in another
    for ch in another:
        freq[ord(ch)] += 1

    # Check if s can be constructed
    for ch in s:
        freq[ord(ch)] -= 1
        if freq[ord(ch)] < 0:
            return False

    return True


def main():
    s = "hello"
    another = "olehhlxyz"
    print(str(can_construct(s, another)).lower())


if __name__ == "__main__":
    main()




"""
run:

true

"""

 



answered Jan 5 by avibootz
0 votes
from collections import Counter

def can_construct(s: str, another: str) -> bool:
    freq = Counter(another)
    for ch in s:
        freq[ch] -= 1
        if freq[ch] < 0:
            return False
            
    return True


print(str(can_construct("hello", "olehhlxyz")).lower())




"""
run:

true

"""

 



answered Jan 5 by avibootz

Related questions

...