leetcode:242: valid letter dysphorism

Insert picture description here
Solution:
We can use an array to count the number of occurrences of each letter in a string.
By comparing the sameness of the respective statistical arrays to determine whether it is a letter dysphoric word.
There is a title to know that the letters are all lowercase, so the size of the statistical array is 26.

bool isAnagram(string a,string *b)
{
    
    
	int a_count[26]={
    
    0};
	int b_count[26]={
    
    0};
	int i;
	for(i=0;a[i]!='\0';i++)
	{
    
    
		a_count[a[i]-'a']++;
	}
	for(i=0;b[i]!='\0';i++)
	{
    
    
		b_count[b[i]-'a']++;
	}
	for(i=0;i<26;i++)
	{
    
    
		if(a_count[i]!=b_count[i])
		{
    
    
			return false;
		}
	}
	return true;
}

The complete code:

#include<cstdio>
using namespace std;
bool isAnagram(char *a,char *b)
{
    
    
	int a_count[26]={
    
    0};
	int b_count[26]={
    
    0};
	int i;
	for(i=0;a[i]!='\0';i++)
	{
    
    
		a_count[a[i]-'a']++;
	}
	for(i=0;b[i]!='\0';i++)
	{
    
    
		b_count[b[i]-'a']++;
	}
	for(i=0;i<26;i++)
	{
    
    
		if(a_count[i]!=b_count[i])
		{
    
    
			return false;
		}
	}
	return true;
}
int main(void)
{
    
    
	char a[100];
	char b[100];
	scanf("%s %s",a,b);
	printf("%d\n",isAnagram(a,b));
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/115025994