问题描述
小R有一个字符串 word,该字符串由数字和小写英文字母组成。小R想用空格替换每一个不是数字的字符。然后,他希望统计在替换后剩下的整数中,不同整数的数目。
例如,给定字符串 "a123bc34d8ef34",替换后形成的字符串是 " 123 34 8 34",剩下的整数是 "123"、"34"、"8" 和 "34"。不同的整数有三个,即 "123"、"34" 和 "8"。
注意,只有当两个整数的不含前导零的十进制表示不同,才认为它们是不同的整数。
测试样例
样例1:
输入:
word = "a123bc34d8ef34"
输出:3
样例2:
输入:
word = "t1234c23456"
输出:2
样例3:
输入:
word = "a1b01c001d4"
输出:2
数据结构选择
- 列表(List) :用于存储从字符串中提取的数字字符序列。
- 集合(Set) :用于存储不同的整数,因为集合可以自动去重。
算法步骤
- 遍历字符串:从头到尾遍历字符串,找到连续的数字字符序列。
- 提取数字字符序列:当遇到数字字符时,继续向后遍历直到遇到非数字字符,提取出这段连续的数字字符序列。
- 去除前导零:将提取出的数字字符序列转换为整数,去除前导零。
- 去重并统计:将转换后的整数添加到集合中,最后集合的大小即为不同整数的数量。 代码1:
def count_distinct_integers(word): # 替换非数字字符为空格
replaced_word = ''.join(' ' )
if not char.isdigit()
else char for char in word) # 分割成独立的数字字符串
numbers = replaced_word.split() # 去除每个数字字符串的前导零,并存储到集合中
unique_numbers = set(str(int(num))
for num in numbers) # 返回集合的大小
return len(unique_numbers) # 测试样例
print(count_distinct_integers("a123bc34d8ef34")) # 输出: 3 print(count_distinct_integers("t1234c23456")) # 输出: 2 print(count_distinct_integers("a1b01c001d4")) # 输出: 2
代码2:
def solution(word):
numbers = []
i = 0
n = len(word)
# 提取连续的数字字符序列
while i < n:
if word[i].isdigit():
j = i
while j < n and word[j].isdigit():
j += 1
numbers.append(word[i:j])
i = j
else:
i += 1
# 处理数字字符序列并去重
unique_integers = set()
for num_str in numbers:
# 去除前导零并转换为整数
num = int(num_str)
# 如果数字不是0或者原始字符串就是'0',则添加到集合中
if num != 0 or num_str == '0':
unique_integers.add(num)
# 返回不同整数的数目
return len(unique_integers)
# 测试样例
print(solution("a123bc34d8ef34")) # 输出: 3
print(solution("t1234c23456")) # 输出: 2
print(solution("a1b01c001d4")) # 输出: 2
关键步骤
- 提取连续的数字字符序列:使用双指针(
i和j)来提取连续的数字字符序列。 - 去除前导零:将提取出的数字字符序列转换为整数,自动去除前导零。
- 去重并统计:使用集合来存储不同的整数,并返回集合的大小。