如何更改此代码以获得最长的连续 C 序列,而不是任何字符的最长连续序列

How do I change this code to get the longest continuous sequence of Cs rather than the longest continuous sequence of any character

提问人:cora 提问时间:9/18/2022 更新时间:9/18/2022 访问量:43

问:

我做了一个解决方案,为我提供了最长的连续字符序列的值,但是我需要如何修改它以指定我需要字符 C 的最长连续序列?或者我完全需要一个全新的代码块?

using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;

namespace CarCounting
{
    internal class Program
    {
        static void Main(string[] args)
        {
            CarCounting newSequence = new CarCounting();   
            Console.WriteLine(newSequence.longest("CCMCCCCLLCCC")); //executes the function
  
        }
    }

    public class CarCounting
    {

        public CarCounting()
        {

        }


        public int longest(string mySequence)
        {
            //turns the argument into an array
            char[] charC = new char[mySequence.Length]; 
            for (int i = 0; i < mySequence.Length; i++) 
            {
                charC[i] = mySequence[i];
            }

            int charCcount = 0;
            int length = charC.Length;
            
            //compares the values in the array
            for(int i = 0; i < length; i++)  
            {
                int currentcount = 1;
                for (int j = i + 1; j < length; j++) 
                {
                    if (charC[i] != charC[j]) 
                        break;
                    currentcount++;
                }
                if (currentcount > charCcount)
                {
                    charCcount = currentcount;
                }
            }


            return charCcount;

        }

    }

}
C# 序列

评论


答:

0赞 Tim Schmelter 9/18/2022 #1

如果你看到不是你搜索的那个,你必须进入外循环:continuechar

public int Longest(string mySequence, char c = '\0')
{
    // ...
    for (int i = 0; i < length; i++)
        if (c != '\0' && mySequence[i]!= c) 
            continue;
        // ...

演示:https://dotnetfiddle.net/5pYxbJ

请注意,您不需要用 中的字符填充 。您可以将任何字符串视为 .只需使用索引器即可。如果确实需要 ,请使用 ToCharArray。我已经在我的演示中更改了您的代码以显示我的意思。char[]stringchar[]char[]