📌  相关文章
📜  Python|检查字符串的所有字符的频率是否不同

📅  最后修改于: 2022-05-13 01:57:05.105000             🧑  作者: Mango

Python|检查字符串的所有字符的频率是否不同

给定一个仅由小写字母组成的字符串S ,任务是检查字符串中所有字符的频率是否唯一。

例子:

Input : abaccc
Output : Yes
‘a’  occurs two times, ‘b’ occurs once
and ‘c’ occurs three times.

Input : aabbc
Output : No
Frequency of both 'a' and 'b' are same.

方法:
在这个问题中要观察的一件事是字符的位置在这里无关紧要,只需计算字符的频率即可。遍历字符串并计算所有字符的出现次数。然后对频率数组进行排序,检查连续元素是否相同,立即打印“否”,否则打印“是”。

# Python program to check if frequency of
# all characters of a string are unique
    
    # creating a frequency array 
    freq =[0]*26
    
    # Finding length of s 
    n = len(s) 
    
    for i in range(n): 
    
        # counting frequency of all characters 
        freq[ord(s[i])-97] += 1
  
    # sorting the frequency array
    freq.sort()
    for i in range(25): 
    
        # checking if element is zero
        if (freq[i] == 0):
            continue
  
        # if element is non-zero
        # checking if frequencies are unique
        if (freq[i] == freq[i + 1]): 
            return False
  
    return True
    
# Driver code 
s ="abaccc"
  
if(check(s)): 
    print("Yes") 
else: 
    print("No") 
输出:
Yes