valid password

  • 0

    You would like to set a password for an email account. However, there are two restrictions on the format of the passowrd. It has to contain at least one uppercase character and it cannot contain any digits.

    You are given a string S consisting of N alphanumerical characters. You would like to find the longest substring of S that is a valid password. A substring is defined as a contiguous segment of a string.

    For example, given "a0Ba", the substrings that are valid passowrds are "B" and "Ba". Note that "aBa" is not a substring and 'a0B' is not a valid password.

    Write a function that givne a non-empty string S consisting of N characters, returns the length of the longest substring that is a valid password. If there is not such substring, your function should return -1.

    Example 1:
    S = "a0Ba"

    return 2

    Example 2:
    S = "a0bb"

    return -1

  • 0

    python solution:

    def valid_password(s):
        left, right, max_length = 0, 0, 0
        while right < len(s):
            while right < len(s) and s[right].isdigit():
                right += 1
            left = right
            found_upper = False
            while right < len(s) and not s[right].isdigit():
                if s[right].isupper():
                    found_upper = True
                right += 1
            if found_upper:
                max_length = max(max_length, right - left)
        return -1 if max_length == 0 else max_length

Log in to reply

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