In this example, a function is used to return the most frequently occurring characters in the input string.
Code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. collections;
Namespace stringtest
{
Class Program
{
Static void main (string [] ARGs)
{
String d = findmaxchar ("abcdadccca ");
}
Private Static string findmaxchar (string value)
{
// Compute the numbers of each char and store it in hashTable
Hashtable ht = new Hashtable ();
For (int I = 0; I <value. Length; I ++)
{
If (! Ht. ContainsKey (value. Substring (I, 1 )))
{
Ht. Add (value. Substring (I, 1), GetCount (value, value. Substring (I, 1 )));
}
}
Int temp;
String maxStr = string. Empty;
List <int> lt = new List <int> ();
Foreach (System. Collections. DictionaryEntry objDE in ht)
{
Lt. Add (convert. toint32 (objde. Value ));
}
// Get the max num.
For (INT I = 0; I <lt. Count-1; I ++)
{
If (LT [I]> lt [I + 1])
{
Temp = lt [I + 1];
Lt [I + 1] = lt [I];
Lt [I] = temp;
}
}
// Get the max char.
Foreach (System. Collections. DictionaryEntry objDE in ht)
{
If (objDE. Value. ToString () = lt [lt. Count-1]. ToString ())
{
MaxStr = objDE. Key. ToString ();
}
}
Return maxStr;
}
// Get the count of char.
Private static int GetCount (string orignal, string strTarget)
{
Int count = 0;
For (int I = 0; (I = orignal. IndexOf (strTarget, I)> = 0; I ++)
{
Count ++;
}
Return count;
}
}
}
In this example, the time complexity is relatively large, so there is a lot of room for optimization.
After further optimization with a friend (communication), the time complexity of the Code is greatly reduced.
Private Static string findmaxchar (string value)
{
Hashtable ht = new hashtable ();
For (INT I = 0; I <value. length; I ++)
{
If (ht [value [I] = null)
Ht. Add (value [I], 1 );
Else
Ht [value [I] = int. Parse (ht [value [I]. ToString () + 1;
}
DictionaryEntry maxItem = new DictionaryEntry ();
MaxItem. Value = 0;
Foreach (DictionaryEntry item in ht)
{
If (Int32.Parse (maxItem. Value. ToString () <Int32.Parse (item. Value. ToString ()))
MaxItem = item;
}
Return maxItem. Key. ToString ();
}