有一个字符串由数字和英文字母组成或只有数字或只有字母,现需要统计英文字母出现的次数,并按出现次数从大到小依次输出这些英文字母和其出现的次数。注:
1. 出现次数相同的不同字符按字典序小的排列在前,字典序大的排列在后
2. 若字符串中没有英文字母,请返回字符串"0"
有一个字符串由数字和英文字母组成或只有数字或只有字母,现需要统计英文字母出现的次数,并按出现次数从大到小依次输出这些英文字母和其出现的次数。注:
输入数据为 字符串(数字字母组合 or 纯英文字母 or 纯数字 )
数据范围:0 <= 字符串的长度 <= 20
输出数据为 字符串(每个英文字母后跟该字母出现的次数)
注:
1. 出现次数相同的不同字符按字典序小的排列在前,字典序大的排列在后
2. 若字符串中没有英文字母,请返回字符串"0"
"AAAB1ccb5"
"A3c2B1b1"
import java.util.*;
public class Solution {
/**
*
* @param input string字符串
* @return string字符串
*/
public String printOutput (String input) {
// write code here
TreeMap<Character,Integer>map=new TreeMap<>();
int count=0;
for(int i=0;i<input.length();i++){
char s=input.charAt(i);
if(Character.isLetter(s)){
if(!map.containsKey(s)){
map.put(s,1);
}else{
map.put(s,map.get(s)+1);
}
count++;
}else{
continue;
}
}
if(count==0){
return "0";
}
StringBuilder sb=new StringBuilder();
Set<Character> set = map.keySet();
while(!map.isEmpty()) {
// 通过遍历每一个key的值,获取到对应的value值
int maxValue = 0;
Character maxZiFu = null;
for(Character cha : set) {
int value= map.get(cha);
if(value > maxValue) {// 为了将当前map集合中的最大值获取到
maxValue = value;
maxZiFu = cha;
}
}
sb.append(String.valueOf(maxZiFu));
sb.append(String.valueOf(maxValue));
//将最大的键值对输出之后,从map集合中删除
map.remove(maxZiFu);
}
return sb.toString();
}
} # # # @param input string字符串 # @return string字符串 # from collections import defaultdict class Solution: def printOutput(self , input ): # write code here d = defaultdict(int) for c in input: if c.isalpha(): d[c] += 1 if len(d) == 0:return "0" ans = sorted(d.items(), key=lambda x: (-x[1], x[0])) res = "" for a in ans: res += a[0] + str(a[1]) return res
class Solution:
def printOutput(self , input ):
dic ={}
temp = input
for i in temp:
if not str(0) <= str(i) <= str(9):
if i in dic:
dic[i] += 1
else:
dic[i] = 1
if dic == {}:
return "0"
else:
temp = list(dic.items())
temp.sort(key=lambda x:x[1], reverse=True)
ans = ""
for i in range(0,len(temp)):
ans += temp[i][0]
ans += str(temp[i][1])
return ans