leetcode - 2264. Largest 3-Same-Digit Number in String

Description

You are given a string num representing a large integer. An integer is good if it meets the following conditions:

It is a substring of num with length 3.
It consists of only one unique digit.
Return the maximum good integer as a string or an empty string "" if no such integer exists.

Note:

A substring is a contiguous sequence of characters within a string.
There may be leading zeroes in num or a good integer.

Example 1:

Input: num = "6777133339"
Output: "777"
Explanation: There are two distinct good integers: "777" and "333".
"777" is the largest, so we return "777".

Example 2:

Input: num = "2300019"
Output: "000"
Explanation: "000" is the only good integer.

Example 3:

Input: num = "42352338"
Output: ""
Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.

Constraints:

3 <= num.length <= 1000
num only consists of digits.

Solution

Sliding window

A window could expand only when: a). the new element is the same, b) the length of the window is smaller than 3.

Since right is the new element in the window, and left is also in the window, the length of the window is right - left + 1.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Enumerate

Since the answer is only 000, 111, 222, ..., we could just enumerate from 999 to 000. If it exists in the num then return, otherwise return an empty string.

Time complexity: o ( n ) o(n) o(n) because of in
Space complexity: o ( 1 ) o(1) o(1)

Code

Sliding window

class Solution:
    def largestGoodInteger(self, num: str) -> str:
        left = 0
        res_num = -1
        for right in range(len(num)):
            while num[left] != num[right] or right - left + 1 > 3:
                left += 1
            if right - left + 1 == 3:
                res_num = max(res_num, int(num[left: right + 1]))
        if res_num == -1:
            res = ''
        elif res_num == 0:
            res = '000'
        else:
            res = str(res_num)
        return res

Enumerate

class Solution:
    def largestGoodInteger(self, num: str) -> str:
        for i in range(9, -1, -1):
            cur_char = str(i) * 3
            if cur_char in num:
                return cur_char
        return ''

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)