Python solution with detailed explanation


  • 0
    G

    Student Attendance Record I https://leetcode.com/problems/student-attendance-record-i/description/

    Count Absents and longest late streak

    • Absents must be <= 1. Longest late streat must be <= 2.
    class Solution(object):
        def checkRecord(self, s):
            """
            :type s: str
            :rtype: bool
            """
            absent, longest_late = 0, 0
            start, end = None, None
            for idx, att in enumerate(s):
                if att == "A":
                    absent += 1
                    start = None
                elif att == "P":
                    start = None
                elif att == "L":
                    end = idx
                    start = idx if start is None else start
                    longest_late = max(longest_late, end-start+1)
            return True if absent <= 1 and longest_late <= 2 else False
    

    1 liner using count and in

    • Count number of A and check if "LLL" is in s or not.
    class Solution(object):
        def checkRecord(self, s):
            """
            :type s: str
            :rtype: bool
            """
            return s.count("A") <= 1 and "LLL" not in s
    
    

    Linear scan count "A" and test for pattern "LLL" in s

    class Solution(object):
        def checkRecord(self, s):
            """
            :type s: str
            :rtype: bool
            """
            absent = 0
            for idx, att in enumerate(s):
                if att == "A":
                    absent += 1
                    if absent > 1:
                        return False
                elif s[idx] == "L" and idx > 1 and s[idx-1] == "L" and s[idx-2] == "L":
                    return False
            return True
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.