0

我需要一些帮助。我正在编写一个代码C++,最终将传入一个随机字符串,它会在字符串中的每个点进行中断,并计算中断右侧和左侧的颜色数(r,b , 和 w)。这就是问题所在,w可以是,r或者b当它破裂时,或者当强者通过它时,最终使它成为一个混合体。我的问题是,当中断被实施并且w立即向左或向右时,我无法让程序去寻找拳头br. 谁能帮我?

#include <stdio.h>
#include "P2Library.h"

void doubleNecklace(char neck[], char doubleNeck[], int size);
int findMaxBeads(char neck2[], int size);
#define SIZE 7

void main(void)
{
    char necklace[SIZE];
    char necklace2[2 * SIZE];
    int brk;
    int maxBeads;
    int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
    char leftColor, rightColor;
    initNecklace(necklace, SIZE);

    doubleNecklace(necklace, necklace2, SIZE);
    maxBeads = findMaxBeads(necklace2, SIZE * 2);
    checkAnswer(necklace, SIZE, maxBeads);

    printf("The max number of beads is %d\n", maxBeads);
}

int findMaxBeads(char neck2[], int size)
{
    int brk;
    int maxBeads;
    int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
    char leftColor, rightColor;

    for(brk = 0; brk < 2 * SIZE - 1; brk++)
    {
        leftCount = rightCount = 0;
        rightI = brk;
        rightColor = neck2[rightI];

        if(rightI == 'w')
        {
            while(rightI == 'w')
            {
                rightI++;
            }
            rightColor = neck2[rightI];
        }
        rightI = brk;

        while(neck2[rightI] == rightColor || neck2[rightI] == 'w')
        {
            rightCount++;
            rightI++;
        }

        if(brk > 0)
        {
            leftI = brk - 1;
            leftColor = neck2[leftI];

            if(leftI == 'w')
            {
                while(leftI == 'w')
                {
                    leftI--;
                }
                leftColor = neck2[leftI];
            }
            leftI = brk - 1;

            while(leftI >= 0 && neck2[leftI] == leftColor || neck2[leftI] == 'w')
            {
                leftCount++;
                leftI--;
            }
        }
        totalCount = leftCount + rightCount;
        if(totalCount > maxCount)
        {
            maxCount = totalCount;
        }
    }
    return maxCount;
}

void doubleNecklace(char neck[], char doubleNeck[], int size)
{
    int i;
    for(i = 0; i < size; i++)
    {
        doubleNeck[i] = neck[i];
        doubleNeck[i+size] = neck[i];
    }
}
4

1 回答 1

0

我没有详细研究代码,但有些东西不是对称的:在for循环中,“左”代码有一个if但“右”代码没有。也许您应该-1for条件中删除它并将其添加if为“正确”代码:

for(brk = 0; brk < 2 * SIZE; brk++)
{
    leftCount = rightCount = 0;

    if (brk < 2 * SIZE - 1)
    {
        rightI = brk;
        rightColor = neck2[rightI];

        //...
    }

    if(brk > 0)
    {
        leftI = brk - 1;
        leftColor = neck2[leftI];

        //...
    }

    //...

只是猜测... :-/

也许您甚至应该将这些更改<<=.

于 2013-03-08T07:38:37.607 回答