N
N
Nikita Kushchenko2021-10-26 16:26:10
C++ / C#
Nikita Kushchenko, 2021-10-26 16:26:10

How to determine whether it is possible to create a string identical to the second array from the characters of the first array?

Two arrays are entered. How to determine whether it is possible to create a string identical to the second array from the characters of the first array? The difficulty is that the first array can have several identical characters, and when sorting and comparing arrays, the code does not work correctly, in theory, from the characters of the first "aboba" array, you can create a string identical to the second "abob" array, but the program says that it is impossible because in the first array has two characters 'a'.

#include <iostream>
#include <algorithm>

bool isPermutation(char* str1, char* str2, int size)
{
    std::sort(str1, str1 + size);
    std::sort(str2, str2 + size);
    
    for (int i = 0; i < size; ++i)
    {
        if (str1[i] != str2[i])
            return false;
    }

    return true;
}


int main()
{
    const int size = 256;
    char* str1 = new char[size];
    char* str2 = new char[size];
    std::cin >> str1 >> str2;
    std::cout << isPermutation(str1, str2, 256);
    delete[] str1;
    delete[] str2;
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-10-26
@wataru

Count how many of each character occurs in the first line and make sure there are no more in the second.
The easiest way to do this is to create an array of counters with 256 elements. For the characters of the first line, increase the counter by index by 1, for the second line, subtract 1. If you get -1 somewhere, then you can't compose. And yet, this is your C ++, judging by the tags and cin? Well, use std::string. What for you allocate lines? static_cast<int>(s[i])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question