Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out how long the longest sequence is in a string

Tags:

c#

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;
    }
like image 509
Tommy Avatar asked Jan 21 '23 15:01

Tommy


1 Answers

This will return 0 for strings of length 1 (when it should return 1).

like image 131
Henrik Avatar answered Feb 03 '23 18:02

Henrik