件名:383。身代金の手紙
身代金の文字(身代金)の文字列と雑誌(雑誌)の文字列が与えられた場合、最初の文字列の身代金が2番目の文字列の雑誌の文字で構成できるかどうかを判断します。形成できる場合はtrueを返し、そうでない場合はfalseを返します。
回答
アイデア:絶対的な位置
bool canConstruct(char* ransomNote, char* magazine)
{
int ASCLL[130] = {
0};
while(*magazine != '\0')
{
ASCLL[*magazine]++;
magazine++;
}
while(*ransomNote != '\0')
{
ASCLL[*ransomNote]--;
ransomNote++;
}
for(int i = 0;i < 130;i++)
{
if(ASCLL[i] < 0)
return false;
}
return true;
}
アイデア:相対位置
bool canConstruct(char * ransomNote, char * magazine){
int ASCLL[26]={
0};
while (*magazine != '\0')
{
ASCLL[*magazine -'a']++;
magazine++;
}
while (*ransomNote != '\0')
{
ASCLL[*ransomNote-'a']--;
if (ASCLL[*ransomNote-'a']<0)
{
return false;
}
ransomNote++;
}
return true;
}