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

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool canConstruct(const char *str, const char *anotherstr) {
    int freq[256] = {0};   // count all ASCII chars

    // Count characters in anotherstr
    for (const unsigned char *p = (const unsigned char *)anotherstr; *p; p++)
        freq[*p]++;

    // Check if str can be constructed
    for (const unsigned char *p = (const unsigned char *)str; *p; p++) {
        if (--freq[*p] < 0)
            return false;
    }

    return true;
}

int main(void) {
    const char *str = "hello";
    const char *anotherstr = "olehhlxyz";

    printf("%s\n", canConstruct(str, anotherstr) ? "true" : "false");
    
    return 0;
}




/*
run:

true

*/

 



answered Jan 5 by avibootz

Related questions

...