leetcode 1805. Number of Different Integers in a String(python)

描述

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example, “a123bc34d8ef34” will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: “123”, “34”, “8”, and “34”.

Return the number of different integers after performing the replacement operations on word.

Two integers are considered different if their decimal representations without any leading zeros are different.

Example 1:

Input: word = "a123bc34d8ef34"
Output: 3
Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.	

Example 2:

Input: word = "leet1234code234"
Output: 2

Example 3:

Input: word = "a1b01c001"
Output: 1
Explanation: The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.

Note:

1 <= word.length <= 1000
word consists of digits and lowercase English letters.

解析

根据题意,只需要找到字符串 word 中的所有合法的数字个数即可,如果是纯字母则直接返回 0 ,否则先使用到了正则来提取 word 中的所有数字字符串,然后将所有大于 9 的数字字符串的前置 0 都去除,然后对结果列表进行去重计算个数即可。

解答

class Solution(object):
    def numDifferentIntegers(self, word):
        """
        :type word: str
        :rtype: int
        """
        if word.isalpha():
            return 0
        r = re.findall('[0-9]{1,}', word)
        r = [num[:-1].lstrip('0')+num[-1] for num in r if len(num)>0]
        return len(set(r))

运行结果

Runtime: 16 ms, faster than 93.84% of Python online submissions for Number of Different Integers in a String.
Memory Usage: 13.3 MB, less than 98.34% of Python online submissions for Number of Different Integers in a String.

原题链接:https://leetcode.com/problems/number-of-different-integers-in-a-string/

您的支持是我最大的动力

你可能感兴趣的:(leetcode,leetcode,python,算法)