牛客题解 | 构建短字符串
题目
题解
难度:简单
知识点:map、字符串
解题分析:判断长字符串是否含短字符串时,主要通过长字符串含的字符及数量是否足够搭建短字符,所以可以使用map形成一个<char,int>的形式来判断,也可以使用数组来统计字符的数量来进行计算。
方法一
主要使用map形成一个<char,int>的对应方式来统计。
#include <bits stdc++.h>
using namespace std;
int main()
{
string str1,str2;
cin>>str1>>str2;
map<char,int> m;
bool flag = true; //用来判断能不能构建短字符串
for(auto it : str2)
m[it]++;
for(auto it : str1)
{
if(m[it])
m[it]--;
else
flag = false;
}
if(flag)
cout<<"true";
else
cout<<"false";
return 0;
}
方法二
因为字符是由26个组成,所以直接使用一个int[26]的数组来进行统计计算。
#include <bits stdc++.h>
using namespace std;
int main()
{
string str1,str2;
cin>>str1>>str2;
int str[26]={0};
bool flag=true;
for(auto it : str2)
{
int num=it-'a';
str[num]++;
}
for(auto it : str1)
{
int num =it-'a';
str[num]--;
if(str[num]<0)
flag=false;
}
if(flag)
cout<<"true";
else
cout<<"false";
return 0;
}
</char,int></char,int></char,int>

浙公网安备 33010602011771号