【问题标题】:combinatorial problem with counting student attendance [closed]计算学生出勤率的组合问题[关闭]
【发布时间】:2018-09-13 19:35:39
【问题描述】:

我该如何解决这个问题?

输入: s - 字符串 (n

缺席
l 迟到
p代表现在

如果连续字母'aaa'则输出:学生不允许参加考试 如果字符串有超过 4 个 'L' 则输出:学生不允许参加考试

else - 允许学生参加考试。

示例:

输入:PPPPPLLLL
输出:学生不允许参加考试

输入:PLPLPPPAAA
输出:不允许学生参加考试

输入:APLPLLPPAP
输出:允许学生参加考试

我需要一个组合公式。但是如何应用它以及哪一个?

【问题讨论】:

  • 回复:“我需要一个组合公式”:你为什么这么说?

标签: java algorithm combinations


【解决方案1】:

最简单和最天真的解决方案是在最差的O(n) 复杂性中遍历所有字符 - 实际上,我不知道有什么更好的解决方案。 100'000 迭代不是 Java 无法处理的。

int consecutiveA = 0;                                          // Absent counter
int consecutiveL = 0;                                          // Late counter

boolean flag = true;

for (char ch: s.toLowerCase().toCharArray()) {                 // Iterate through the chars
    if (ch == 'a') {                                           // Checks the absent
        consecutiveL = 0;
        consecutiveA++;
    } else if (ch == 'l') {                                    // Checks the late
        consecutiveA = 0;
        consecutiveL++;
    } else {                                                   // Or else reset counters
        consecutiveA = 0;
        consecutiveL = 0;
    }
    if (consecutiveA == 3 || consecutiveL == 4) {              // If the condition is met
        System.out.println("Student is not allowed to exam."); // Print it out
        flag = false;                                          // Sets the flag
        break;                                                 // And leave the cycle
    }
}

if (flag) {                                                   
    System.out.println("Student is allowed to exam.");
}

注意关键部分也是break关键字的使用,它使循环停止并离开for-cycle。这可以节省对大量字符的检查,并避免多次打印"Student is not allowed to exam."

有问题的部分可能是字母是否混合了大小写(我的 sn-p)。如果您确定只会出现一种情况,则String::toLowerCase() 可能会被省略。

【讨论】:

  • 我相信这里有一个错误。如果我的出勤记录是 ALALA 或 LLALL,我将被禁止参加考试。我认为这不符合规范。
  • @DawoodibnKareem:好点子!不敢相信我错过了。非常感谢,我修好了。
  • 我不认为你确实修复了这个错误。我认为您刚刚引入了一个新错误。
  • @DawoodibnKareem:嗯,又一次尝试?我认为它现在应该可以工作了。
  • 是的,看起来更好。在这里,投赞成票。
【解决方案2】:

我正在阅读要求字符串中任何位置超过 4 个 L 会阻止学生参加考试 - 它们不必是连续的。另外,我假设所有字符都是大写的。

我认为最短的 Java 解决方案是这样的:

static boolean canTakeExam(String s)
{
    return !s.contains("AAA") && s.replaceAll("[^L]", "").length() < 4;
}

但更有效的实现方式是:

static boolean canTakeExam(String s)
{
    for(int i=0, ca=0, cl=0; i<s.length(); i++)
    {
        char c = s.charAt(i);
        if(c == 'A')
        {
            if(++ca == 3) return false;
        }
        else
        {
            if(c == 'L' && ++cl == 4) return false;
            ca = 0;
        }
    }
    return true;
}

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多