给定一个由小写英文字母组成的字符串S ,任务是找到字符串存在的唯一字符的数量。
例子:
Input: S = “geeksforgeeks”
Output: 7
Explanation: The given string “geeksforgeeks” contains 6 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}.
Input: S = “madam”
Output: 3
方法:解决给定问题的想法是在Python初始化一个 Set() 来存储给定字符串的所有不同字符,然后将集合的大小打印为所需的答案。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to count the number of distinct
# characters present in the string str
def countDis(str):
# Stores all distinct characters
s = set(str)
# Return the size of the set
return len(s)
# Driver Code
if __name__ == "__main__":
# Given string S
S = "geeksforgeeks"
print(countDis(S))
Python3
# Python program for the above approach
from collections import Counter
# Function to count the number of distinct
# characters present in the string str
def countDis(str):
# Stores all frequencies
freq = Counter(str)
# Return the size of the freq dictionary
return len(freq)
# Driver Code
if __name__ == "__main__":
# Given string S
S = "geeksforgeeks"
print(countDis(S))
# This code is contributed by vikkycirus
输出:
7
时间复杂度: O(N)
辅助空间: O(1)
方法二:使用计数器函数:
使用 Counter函数计算所有元素的频率,该频率字典的键数给出结果。
下面是实现:
蟒蛇3
# Python program for the above approach
from collections import Counter
# Function to count the number of distinct
# characters present in the string str
def countDis(str):
# Stores all frequencies
freq = Counter(str)
# Return the size of the freq dictionary
return len(freq)
# Driver Code
if __name__ == "__main__":
# Given string S
S = "geeksforgeeks"
print(countDis(S))
# This code is contributed by vikkycirus
输出:
7
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。