LC 13 & LC 551


Solution to LeetCode 13 Roman to Integer & LeetCode 551 Student Attendance Record I.

LeetCode 13

Roman to Integer (Easy). [link]

Time complexity O(n), space complexity O(1).

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        hash = {'I': 1, 'V': 5,
                'X': 10, 'L': 50,
                'C': 100, 'D': 500,
                'M': 1000}
        pre = ''
        res = 0
        for char in s:
            res += hash[char]
            if pre and hash[char] > hash[pre]:
                res -= 2 * hash[pre]
            pre = char
        return res

LeetCode 551

Student Attendance Record I (Easy). [link]

class Solution(object):
    def checkRecord(self, s):
        """
        :type s: str
        :rtype: bool
        """
        a = 0
        l = 0
        for char in s:
            if char == 'A': a += 1
            if char == 'L': 
                l += 1
            else:
                l = 0
            if a > 1 or l > 2:
                return False
        return True

Solution in one line.

class Solution(object):
    def checkRecord(self, s):
        """
        :type s: str
        :rtype: bool
        """
        return 'LLL' not in s and s.count('A') < 2

  TOC