📜  计算Python中字符串中唯一字符的数量

📅  最后修改于: 2021-10-27 07:50:51             🧑  作者: Mango

给定一个由小写英文字母组成的字符串S ,任务是找到字符串存在的唯一字符的数量。

例子:

方法:解决给定问题的想法是在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 现场工作专业课程学生竞争性编程现场课程