日期:2014-05-20  浏览次数:20786 次

用最少的代码从一个字符串中找到出现频率最高的字符
抛砖引玉
C# code
public static void ThirdWay(string str)
        {
            var resultGroup = from aChar in str.ToCharArray()
                              group aChar by aChar;

            int max = 0;

            foreach (var one in resultGroup)
            {
                if (one.Count() > 0)
                {
                    max = one.Count();
                }
            }

            foreach (var one in resultGroup)
            {
                if (one.Count() == max)
                {
                    Console.WriteLine("{0}字符出现了{1}次", one.Key, max);
                }
            }

        }



------解决方案--------------------
用正则
------解决方案--------------------
string str = "abcdacbdeidaadbefsadaac";
char[] ary = str.ToCharArray();
ArrayList al = new ArrayList();
foreach (char c in ary)

if(!al.Contains(c))
{
Regex reg = new Regex(c.ToString());
al.Add(reg.Matches(str).Count.ToString()+"|"+c.ToString());
}
}
al.Sort();
Response.Write(al[al.Count - 1].ToString());
------解决方案--------------------
char c = str.ToCharArray().GroupBy(ch => ch).OrderBy( g => -g.Count() ).First().Key;
------解决方案--------------------
linq:

var resultGroup = from aChar in str.ToCharArray()
group aChar by aChar into g orderby g.Count() descending select g ;

------解决方案--------------------
探讨
char c = str.ToCharArray().GroupBy(ch => ch).OrderBy( g => -g.Count() ).First().Key;

------解决方案--------------------
C# code

        public static void ThirdWay(string str)
        {
            var group = from c in str group c by c into g orderby g.Count() descending select g;
            Console.WriteLine("{0}字符出现了{1}次",group.First().Key,group.First().Count());
        }

------解决方案--------------------
探讨
char c = str.ToCharArray().GroupBy(ch => ch).OrderBy( g => -g.Count() ).First().Key;

------解决方案--------------------
探讨
引用:

char c = str.ToCharArray().GroupBy(ch => ch).OrderBy( g => -g.Count() ).First().Key;

疯了,疯了!

------解决方案--------------------
真是学习了,厉害!
------解决方案--------------------
看来你得好好学了
------解决方案--------------------
对于“快速”地coding有关搜索和查找方面功能的方法,就去看
IEnumerable<>和 lambda 语法。

这里的“快速”指的是coding速度……而实际的程序执行的效率上实在是……
------解决方案--------------------
自从有了LINQ, 编程就失去了很多乐趣!!
WIN平台上,以后还有真正的程序员么?
------解决方案--------------------
C# code
public static void MostChar(string input)
    {
        int maxCount = 0; char maxChar = '\0';
        while (input.Length > 0)
        {
            char tempChar = input[0];
            int count = input.Length 
                - (input = input.Replace(input[0].ToString(), string.Empty)).Length;
            if (count > maxCount)
            {
                maxCount = count;
                maxChar = tempChar;
            }
        }
        Console.WriteLine("{0}, {1}", maxChar, maxCount);
    }