1. 程式人生 > >C#LeetCode刷題之#551-學生出勤紀錄 I(Student Attendance Record I)

C#LeetCode刷題之#551-學生出勤紀錄 I(Student Attendance Record I)

問題

給定一個字串來代表一個學生的出勤紀錄,這個紀錄僅包含以下三個字元:

'A' : Absent,缺勤
'L' : Late,遲到
'P' : Present,到場
如果一個學生的出勤紀錄中不超過一個'A'(缺勤)並且不超過兩個連續的'L'(遲到),那麼這個學生會被獎賞。

你需要根據這個學生的出勤紀錄判斷他是否會被獎賞。

輸入: "PPALLP"

輸出: True

輸入: "PPALLL"

輸出: False


You are given a string representing an attendance record for a student. The record only contains the following three characters:
'A' : Absent.
'L' : Late.
'P' : Present.
A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

Input: "PPALLP"

Output: True

Input: "PPALLL"

Output: False


示例

public class Program {

    public static void Main(string[] args) {
        var s = "PPALLP";

        var res = CheckRecord(s);
        Console.WriteLine(res);

        s = "AAAA";

        res = CheckRecord2(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool CheckRecord(string s) {
        //一些小技巧
        var boolA = (s.Length - s.Replace("A", "").Length) <= 1;
        var boolL = (s.Length == s.Replace("LLL", "").Length);
        return boolA && boolL;
    }

    private static bool CheckRecord2(string s) {
        //傳統計數法
        var countA = 0;
        var countL = 0;
        foreach(var c in s) {
            if(c == 'A') ++countA;
            if(c == 'L') ++countL;
            else countL = 0;
            if(countA > 1 || countL > 2) return false;
        }
        return true;
    }

}

以上給出2種演算法實現,以下是這個案例的輸出結果:

True
False

分析:

因為使用了部分執行庫,不能簡單的認為 CheckRecord 的時間複雜度為 O(1) 。以上2種演算法的時間複雜度均為 O(n) 。