Came across this problem on one of the programming websites.
The idea is to find the largest sub-string from the given string where the letters are in alphabetical order.
Here is the solution in C# :
int cn = 1;
ArrayList ar = new ArrayList();
string s = "stringtofind";
byte[] asciiBytes = Encoding.ASCII.GetBytes(s);
for (int i = 0; i < asciiBytes.Length; i++)
{
try
{
if (int.Parse(asciiBytes[i].ToString()) <= int.Parse(asciiBytes[i + 1].ToString()))
{
cn += 1;
}
else
{
ar.Add(cn);
cn = 1;
}
}
catch
{
}
}
MessageBox.Show(FindMax(ar).ToString());
The idea is to find the largest sub-string from the given string where the letters are in alphabetical order.
Here is the solution in C# :
int cn = 1;
ArrayList ar = new ArrayList();
string s = "stringtofind";
byte[] asciiBytes = Encoding.ASCII.GetBytes(s);
for (int i = 0; i < asciiBytes.Length; i++)
{
try
{
if (int.Parse(asciiBytes[i].ToString()) <= int.Parse(asciiBytes[i + 1].ToString()))
{
cn += 1;
}
else
{
ar.Add(cn);
cn = 1;
}
}
catch
{
}
}
MessageBox.Show(FindMax(ar).ToString());
The idea is to iterate through the ASCII values of the characters and compare each character with the next to see if it is greater. If yes, then increment the counter. If no, then add the total to an ArrayList and reset the counter.
The maximum value (integer) in the arraylist is the value of the largest substring, as required.
FindMax is a custom function that you can develop. (iterative).
Comments