简体   繁体   English

检查字符串是否具有相同频率的字符,无论是否删除 1 个字符

[英]check if a string has characters of same frequency with or without the removal of 1 character

I'm trying to write a code to check if a given string satisfies the following conditions:我正在尝试编写代码来检查给定的字符串是否满足以下条件:

  1. all the characters occurring in the same frequency以相同频率出现的所有字符
  2. one character can be removed if necessary to achieve the above condition如果需要达到上述条件,可以删除一个字符

the following code works for some test cases but not for others, can u please help me?以下代码适用于某些测试用例,但不适用于其他测试用例,您能帮帮我吗?

d=0
r=0
def isValid(s):
    # Write your code here
    c =Counter(s) #count no occurences of chars in string
    q=0
    v=c.values() 
    val=list(v)  # convert it to list 
    res=Counter(val)  #count no of equal occurences
    d=res.values() 
    dat=list(d) 
    
    if len(dat)==1:
        r='YES'
        return(r)
    elif len(dat)>1:
        q=dat[1]-1
             
    if q==0:
        r='YES'
        return(r)
    else:
        r='NO'
        return(r)   ```

Try this -试试这个 -

from collections import Counter

s = 'AABBCCDD' # Just a EXAMPLE

def check(x):
    z = []
    for y in s:
        z.append(y)

    a = Counter(z)
    b = dict(a)
    c = list(b.values())
    check_list = []
    for ele in c:
        if ele % 2 != 0:
            check_list.append(ele)
    
    if len(check_list) > 1:
        return False

def isValid(s):
    a = Counter(s)
    b = dict(a)
    c = list(b.values())
    y = []
    for x in c:
        y.append(x)
        if x != y[0]:
            if check(x) == False:
                print('Not Valid')
                return
            
        
    print('Valid')
 
isValid(s) # Calling the function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM