java 8
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println(isValid(scan.next()));
}
private static String isValid(String s) {
if (s == null || s.equals("")) {
return "NO";
}
// frequencies ( hashmap) character : frequency
// contains frequency of each character of given string input
Map<Character, Integer> frequencies = new HashMap<>();
for (char ch : s.toLowerCase().toCharArray())
frequencies.put(ch, frequencies.getOrDefault(ch, 0) + 1);
.................................................. ..................................................... ..................................................... .....
// freqTypesCount ( hashmap)
// frequency_type : number_of_chars_having this frequency_type
Map<Integer, Integer> freqTypesCount = new HashMap<>();
for (int ch : frequencies.values())
freqTypesCount.put(ch, freqTypesCount.getOrDefault(ch, 0) + 1);
if( freqTypesCount.size() == 1){
// it means all the chars of string occurs same number of time
return "YES";
}
else if( freqTypesCount.size() > 2){
// aaabbbbccdd
// a : 3 b: 4 c:2 d:2 --> {3:1, 4:1, 2:2}
// we can't make this string a valid string just by deleting single char
return "NO";
}
else{
int valid_freq = Collections.max(freqTypesCount.entrySet(), Map.Entry.comparingByValue()).getKey();
int deleted = 0;
for (Map.Entry<Character, Integer> entry : frequencies.entrySet())
{
int thisCharCount = entry.getValue();
if(thisCharCount != valid_freq){
if(deleted == 0){
if(thisCharCount - 1 == valid_freq || thisCharCount - 1 == 0){
deleted += 1;
}
else{
return "NO";
}
}
else{
return "NO";
}
}
}
return "YES" ;
}
}
}
.................................................. ..................................................... ..................................................... .....
蟒蛇3
from collections import Counter
inp_string = input()
def isValidStr( string):
char_counter_dict = Counter( string)
count_type_counter_dict = Counter(char_counter_dict.values())
if len(count_type_counter_dict) == 1:
return "YES"
elif len(count_type_counter_dict) > 2:
return "NO"
else:
valid_freq = count_type_counter_dict.most_common()[0][0]
deleted = 0
for char,count in char_counter_dict.items():
if count != valid_freq:
if deleted == 0:
if count - 1 == valid_freq or count - 1 == 0:
deleted += 1
else:
return "NO"
else:
return "NO"
return "YES"
print(isValidStr(inp_string))