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

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>

bool canConstruct(const std::string& str, const std::string& anotherstr) {
    std::vector<int> freq(256, 0); // count all ASCII chars

    for (char ch : anotherstr)
        freq[(unsigned char)ch]++;

    for (char ch : str) {
        if (--freq[(unsigned char)ch] < 0)
            return false; // anotherstr doesn't have enough of this char
    }

    return true;
}

int main() {
    std::string str = "hello";
    std::string anotherstr = "olehhlxyz";

    std::cout << std::boolalpha << canConstruct(str, anotherstr);
}



/*
run:

true

*/

 



answered Jan 5 by avibootz
edited Jan 5 by avibootz

Related questions

...