Python regex solution


  • 0
    L

    Python2

    class Solution(object):
        def detectCapitalUse(self, word):
            """
            :type word: str
            :rtype: bool
            """
            import re
            return True if re.match(r'[A-Z]+\Z|[A-Z]?[a-z]+\Z', word) else False
            # or
            # return True if re.match(r'^[A-Z]+$|^[A-Z]?[a-z]+$', word) else False
    

    Python3

    class Solution(object):
        def detectCapitalUse(self, word):
            """
            :type word: str
            :rtype: bool
            """
            import re
            return True if re.fullmatch(r'[A-Z]+|[A-Z]?[a-z]+', word) else False

Log in to reply
 

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