算法大比拼(看看谁是真真的高手)?(java C# C++ C的高手请进)
求算一任意长度字符串中不同的字符以及它的个数?(设计一个漂亮的算法,快而优美)
如在 字符串"abcdefgabc"中求算出的结果是
a,2
b,2
c,2
d,1
e,1
f,1
g,1
以一个普通的算法开个头吧.
public static class MyMethod
{
public static Queue<char> GetOnlyCharFromString(string str)
{
Queue<char> myQueue = new Queue<char>();
for (int i = 0; i < str.Length; i++)
{
if (myQueue.Contains(str[i]) == false)
myQueue.Enqueue(str[i]);
}
return myQueue;
}
public static Dictionary<char,int> GetInfoFormString(string str)
{
Queue<char> myQueue = GetOnlyCharFromString(str );
Dictionary<char,int> myDictionary=new Dictionary<char,int>();
int oldQueueCount = myQueue.Count;//记录下它原有的量;
for(int i=0;i<oldQueueCount ;i++)
{
char myChar=myQueue.Dequeue();
int num=0;
for(int j=0;j<str.Length;j++)
{
if(str[j]==myChar)
num++;
}
myDictionary.Add(myChar,num);
}
return myDictionary;
}
}
[解决办法]
不知道效率怎么样
但是这是一个思路
你可以用正则表达式去匹配
从ASCII为0的到128
以下是.NET下正则表达式的使用方法
http://msdn.microsoft.com/zh-cn/library/system.text.regularexpressions.regex(VS.80).aspx
// Define a regular expression for repeated words.
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string.
string text = "The the quick brown fox fox jumped over the lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found.", matches.Count);
// Report on each match.
foreach (Match match in matches)
{
string word = match.Groups["word"].Value;
int index = match.Index;
Console.WriteLine("{0} repeated at position {1}", word, index);
}
[解决办法]
string str = "abcdefgabc"; var result = from c in str group c by c into g select g; foreach (var group in result) Console.WriteLine(group.Key + "," + group.Count());
[解决办法]
C++ Code
int main(void)
{
string str = "abcdeffasljdlfjaslflsadjflkasdfjlsadlfgabc";
sort(str.begin(), str.end());//先排序
cout<<str<<endl;
char c;
int count;
int i = 0;
while(i < str.length()){
c = str[i];
count = 1;
while(c == str[++i]){
count++;
}
cout<<c<<","<<count<<endl;
}
return 0;
}
[解决办法]
declare @a varchar(max) set @a='abcdefgabc'declare @b table(s varchar(1))declare @n intdeclare @i intset @i=1set @n=len(@a)set rowcount @nwhile @i<=@nbegin insert into @b select substring(@a,@i,1) set @i=@i+1endset rowcount 0select count(s),s from @b group by s
[解决办法]
php:
$str = "abcdefgabc";for(;$i<strlen($str);$i++)$astr[]=$str[$i];print_r(array_count_values($astr));