用c# or ASP.NET编写一个方法,求一段字符串中出现频率最的字符?
1、给定一个字符串 string str = "天工网定位于我的建设门户、我的工作社区,倾听用户的声音,关注用户的需求是天工生存与发展的根基,网上会员大都是通过口碑相传得知天工网,并成为天工网的忠实用户";
请用程序找出这个字符串中出现频率最高字
(要求把该方法写成一个函数,然后用main()函数调用该方法,开发语言不限,但不能直接调用系统的方法)
[解决办法]
刚才又想了下,复杂度还是不够满意,哈希的复杂度也不可忽略
换了空间多点的。
严格的O(n)
public char Get(string str)
{
//Dictionary<char, int> dic = new Dictionary<char, int>();
int[] intarray=new int[65535];
char c=new char();
int count = 0;
foreach (char ch in str)
{
intarray[(int)ch] += 1;
if (intarray[(int)ch] > count)
{
count = intarray[(int)ch];
c = ch;
}
//if (dic.ContainsKey(ch))
//{
// dic[ch] += 1;
//}
//else
//{
// dic.Add(ch, 1);
//}
//if (dic[ch] >= count)
//{
// count = dic[ch];
// c = ch;
//}
}
return c;
}
[解决办法]
我第二个没用哈希的 int和char可以互相转换的,任何字符都在65535内,定义一个65535数组,存放对应的count,这个复杂度 绝对是On的