#include<iostream>
#include<string>
using namespace std;
int main()
{
string s, sub;
cin >> s;
int check = 1, count = 0, pos = 0; // keeping count of number of alphabetical ordered substring characters
int i = 1; // loop variable
int prev = 0; //to hold previous value of loop variable
while (i< s.size())
{
check = 1;
while ((int)s[i] >= (int)s[i - 1])
{
++check;
++i;
}
if (check > count)
{
count = check;
pos = i - check;
}
if (i == prev)
++i;
prev = i; //if the inner while loop isn't executed, then i will be incremented here
}
cout << "Longest substring in alphabetical order is :" << s.substr(pos, count) << endl;
}
This was a part of my assignment. I could solve this in 10 minutes but I am not sure if this is a very efficient code. Though a (if any) more efficient algorithm exists for this, it may not make much of a different but I am keen on making all my programs as efficient as possible right from beginning.