找出最长序列是在一个字符串多久 [英] Find out how long the longest sequence is in a string

查看:107
本文介绍了找出最长序列是在一个字符串多久的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在接受采访时这个问题,这是我想出了。任何反馈?



找出最长序列是在一个字符串有多长。例如,字符串abccdeeeeef的答案将是5。

 静态INT LongestSeq(字符串strPass)
{
INT longestSeq = 0;

的char [] = strChars strPass.ToCharArray();

INT numCurrSeq = 1;
的for(int i = 0; I< strChars.Length - 1;我++)
{
如果(strChars [I] == strChars第[i + 1])$ ​​B $ B {
numCurrSeq ++;
}
,否则
{
numCurrSeq = 1;
}

如果(longestSeq< numCurrSeq)
{
longestSeq = numCurrSeq;
}
}

返回longestSeq;
}


解决方案

首评:你不吨需要将其转换为一个字符数组。你可以索引直入字符串



第二个意见:你可以很容易推广为的IEnumerable< T> 如果你想,使用的foreach 和记忆当前项目



第三点意见:我认为的比较 longestSeq numCurrSeq 会比较清楚的:

 如果(numCurrSeq> longestSeq)

要我来说,这更自然的我平时也表达第一的不同部分。


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, using foreach and remembering the "current" item.

Third comment: I think the comparison between longestSeq and numCurrSeq would be clearer as:

if (numCurrSeq > longestSeq)

To me that's more natural as I usually have the varying part of the expression first.

这篇关于找出最长序列是在一个字符串多久的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆