I recently had this question in an interview and this is what I came up with. Any feedback?
Find out how long the longest sequence is in a string. For example, in the string “abccdeeeeef” the answer would be 5.
static int LongestSeq(string strPass)
{
int longestSeq = 0;
char[] strChars = strPass.ToCharArray();
int numCurrSeq = 1;
for (int i = 0; i < strChars.Length - 1; i++)
{
if (strChars[i] == strChars[i + 1])
{
numCurrSeq++;
}
else
{
numCurrSeq = 1;
}
if (longestSeq < numCurrSeq)
{
longestSeq = numCurrSeq;
}
}
return longestSeq;
}
First comment: you don’t need to convert it to a char array. You can index straight into the string.
Second comment: you could easily generalize this to
IEnumerable<T>if you wanted to, usingforeachand remembering the “current” item.Third comment: I think the comparison between
longestSeqandnumCurrSeqwould be clearer as:To me that’s more natural as I usually have the varying part of the expression first.