📅  最后修改于: 2023-12-03 15:42:18.409000             🧑  作者: Mango
这是GATE-CS-2016(套装1)中的第46题。它涉及到字符串和算法,并且需要你使用程序解决。
给定两个由不同字母组成的字符串 s
和 t
,找到 s
中出现次数最少的字符,使得这个字符在 t
中也存在。如果没有这样的字符,则返回 -1。
例如,如果 s = "aba"
且 t = "acb"
,则最小出现次数的字符是 b
,因为它只出现一次,而其他字符 a
出现两次。并且 b
在 t
中也存在。
以下是函数的签名:
def smallest_character(s: str, t: str) -> str:
pass
1 <= len(s), len(t) <= 10^5
,其中的字符只会在 ASCII 码表的 0 到 127 的范围内。s
中出现次数最少的字符并且在 t
中也存在,或者返回 -1,如果没有符合条件的字符。下面是几组输入输出示例:
Input: s = "aba", t = "cbfda"
Output: 'b'
Explanation: b occurs only once in s, and is present in t.
Input: s = "ab", t = "ab"
Output: 'a'
Explanation: both a and b occur once in s. But a is present in t, and b is not.
Input: s = "aaa", t = "bbb"
Output: -1
这是一个常规的字符串和算法问题。一些提示如下:
s
中出现的次数;t
中出现,并且选择其中出现在 t
中的最小字符。一旦找到最小的,就返回它;t
中找到任何出现次数为1的字符,那么就返回 -1。下面是相应的代码实现,最后输出的永远是一个小写字母或 -1:
def smallest_character(s: str, t: str) -> str:
# Initialize a count array to count the characters in s
# 统计 s 中各个字符的出现次数
count = [0] * 128 # Since the input only contains ASCII characters
for c in s:
count[ord(c)] += 1 # ord(c) converts character c to its ASCII code
# Find the smallest character in s that occurs only once, and appears in t
smallest_char = None
for c in s:
if count[ord(c)] == 1 and c in t and (smallest_char is None or c < smallest_char):
smallest_char = c
# If the smallest_char still None try to find any character that occurs only once, and appears in t
if smallest_char is None:
for c in s:
if count[ord(c)] == 1 and c in t:
smallest_char = c
break
return smallest_char if smallest_char is not None else -1
这是一个简单的字符串处理和算法问题,只需要统计各个字符的出现次数并在给定的限制条件下进行判断和选择即可。