Determine whether the string is a word ectopic


s = "anagram", t = "nagaram"
which belongs to ectopic words, the same length, comprising the same letters, the frequency of occurrence of each character is the same, but just in a different order
s = "rat", t = "car "
this does not belong to ectopic words, since the s 'r' is not in t
ideas:
a first to see if the same length of the string, not the same as compared to false
2 to see whether the frequency of occurrence of each character of the same, can be used to hash table. 26 int apply a length of the array. First Traversal string s Then, each character string
stored in the array in terms of the index, while counting
3 Traversal string t, followed by the character corresponding to an array of values minus one, if the case occurs less than 0 then the It does not match the
code is as follows:

int isAnagram(char *s, char *t)
{
	int freq[26];
	int i, j,len_s, len_t,value;
	len_s = strlen(s);
	len_t = strlen(t);
	value = 0;
	memset(freq, 0, 26*4);
	if (len_s != len_t)
		return -1;
	for (i = 0; i < len_s; i++)
	{
		freq[*(s + i) - 'a']+=1;
	}
	for (j = 0; j < len_t; j++)
	{
		freq[*(t + j) - 'a']-=1;
		value = freq[*(t + j) - 'a'];
		if (value < 0)
			return -1;
	}
	return 1;

}

  

Guess you like

Origin www.cnblogs.com/zhanghongfeng/p/11539970.html