根据字母的重复性来计数和打印字母
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据字母的重复性来计数和打印字母相关的知识,希望对你有一定的参考价值。
我有这样一个问题要做:读取一个只由小字符组成的单词,并从重复次数最多的字母开始打印到屏幕上,如果两个字母的重复时间相同,则先打印最小的值。因为要在最短的时间内完成,所以他们建议我使用bufferedread和bufferedwrite。EX:
输入字:
intensified
输出字:
iiieenndfst
我先试了一下
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String word = br.readLine();
int[] f = new int[26];
int maxcont = 0;
StringBuilder rez = new StringBuilder();
for (int i = 0; i < word.length(); i++)
int cont = 0;
for (int j = 0; j < word.length(); j++)
if(word.charAt(i) == word.charAt(j) && word.codePointAt(i) > 96)
f[word.codePointAt(i)-97]++;
cont++;
word = word.replace(word.charAt(i), 'O');
if (maxcont < cont)
maxcont = cont;
while(maxcont != 0)
for (int i = 0; i < f.length; i++)
if (f[i] == maxcont)
for (int j = maxcont; j > 0; j--)
rez.appendCodePoint(i+97);
maxcont--;
bw.write(String.valueOf(rez));
bw.flush();
但它说这需要太多时间,所以我试了这个。
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String word = br.readLine();
int[] f = new int[123];
int maxcont = 0, min = 122, max = 96;
for (int i = 0; i < word.length(); i++)
int cont = 0;
for (int j = 0; j < word.length(); j++)
if(word.charAt(i) == word.charAt(j) && word.codePointAt(i) > 96)
f[word.codePointAt(i)]++;
cont++;
if (word.codePointAt(i) < min && word.codePointAt(i) > 96)
min = word.codePointAt(i);
if (word.codePointAt(i) > max)
max = word.codePointAt(i);
word = word.replace(word.charAt(i), 'O');
if (maxcont < cont)
maxcont = cont;
while(maxcont != 0)
for (int i = min; i <= max; i++)
if (f[i] == maxcont)
for (int j = maxcont; j > 0; j--)
bw.write((char) i);
bw.flush();
maxcont--;
我也有同样的时间问题,那么我可以从哪些方面改进我的代码以使其更快呢?
答案
你的程序逻辑没问题。程序挂起的原因是当有数据需求但输入缓冲区为空时,BufferedReader会挂起。你是想从System.in中读取用户的输入,但还没有,初始化时要写出一条信息给请求输入的用户。
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
System.out.println("Enter the word to be evaluated:"); //Add this line
String word = br.readLine();
以上是关于根据字母的重复性来计数和打印字母的主要内容,如果未能解决你的问题,请参考以下文章
Powershell根据给定的计数选择一个随机字母,并动态地将每个字母分配给一个唯一的变量?