Algorithm backup ---- Compare occurences of each character of two strings(比较两个字符串每个字符出现频率是否一样)
Here are two strings, my task is to compare these two str1 and str2, and get if the occurences of each character of them are equal.
As we know, we can get the ASCII code of a character, so I use an array of size 128(number of basic ASCII code) to mark the occurences of all characters. Array elements are initialized as zero, if a character appear n times in str1, the value of array element pointing to this character will be added n. Correspondingly, the value subtracts its occurence in str2. In the end, if all array elements are 0, the function return true. Otherwise, false will be returned.
Below if the funtion:
/// Compare occurences of each character of two strings
/// </summary>
/// <param name="str1">string 1</param>
/// <param name="str2">string 2</param>
/// <returns>
/// true: equal occurence of each character
/// false: unequal occurence of one or more characters</returns>
public static bool CompareString(string str1, string str2)
{
//Encoding of Chinese characters and the general characters are diferent
//So we should consider them separately
if (str1 == null && str2 == null)
return true;
else if (str1 == null || str2 == null)
return false;
if (str1.Length != str2.Length)
return false;
int[] count = new int[128];
int i, k;
for (k = 0; k < 128; ++k)
{
count[k] = 0;
}
//To save more time, deal with two strings together.
for (i = 0; i < str1.Length && i < str2.Length; ++i)
{
count[(int)str1[i]]++;
count[(int)str2[i]]--;
}
for (; i < str1.Length; ++i)
{
count[(int)str1[i]]++;
}
for (; i < str2.Length; ++i)
{
count[(int)str2[i]]--;
}
for (k = 0; k < 128; ++k)
{
if (count[k] != 0)
return false;
}
return true;
}
As people gradually required computers to understand additional characters and non-printing characters, the ASCII set became restrictive. Yes, we can get extended ASCII codes(Available from here). But here I will give another way to go on with the comparison, even Chiese words are included in the strings:
/// Compare occurences of each character of two strings
/// </summary>
/// <param name="str1">string 1</param>
/// <param name="str2">string 2</param>
/// <returns>
/// true: equal occurence of each character
/// false: unequal occurence of one or more characters</returns>
public static bool CompareString(string str1, string str2)
{
if (str1 == null && str2 == null)
return true;
if (str1 == null || str2 == null)
return false;
if (str1.Length != str2.Length)
return false;
Dictionary<char, int> dic = new Dictionary<char, int>();
int i;
for (i = 0; i < str1.Length; i++)
{
if (dic.ContainsKey(str1[i]))
{
dic[str1[i]]++;
}
else
{
dic.Add(str1[i], 1);
}
}
for (i = 0; i < str2.Length; i++)
{
if (dic.ContainsKey(str2[i]))
{
dic[str2[i]]--;
}
else
{
dic.Add(str2[i], -1);
}
}
foreach (char ch in dic.Keys)
{
if (dic[ch] != 0)
return false;
}
return true;
}