【发布时间】:2012-02-22 20:14:25
【问题描述】:
我今天写了这段代码来检查字符串中每个字符的频率。它运行得很慢。如何改进此代码?
import java.util.*;
public class checkFreq {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Input
System.out.print("Enter a string: ");
String input = s.nextLine();
long t1 = System.currentTimeMillis();
// Convert input to UpperCase
String tmp = input.toUpperCase();
// String to compare
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int aleng = alphabet.length();
for (int l = 0; l < aleng; l++) {
//Run 26 times
int count = 0;
int i = 0;
String tmp2;
while (i < tmp.length() - 1) {
tmp2 = tmp.substring(i, i + 1);
int exist = tmp2.indexOf(alphabet.charAt(l));
if (exist != -1) {
count++;
}
i++;
}//End while
if (count != 0) {
System.out.print(alphabet.charAt(l) + "(" + count + ") ");
}//End if
}// End for
System.out.println();
long t2 = System.currentTimeMillis();
// Count time of process
System.out.println("Time : " + (t2 - t1) + "ms");
}
}
【问题讨论】:
-
@HotLicks...“呃”?这不酷。这家伙是新来的,有一个问题……没必要取笑这家伙。
-
我在一周内开始学习 Java。所以我希望有人帮助找出更有效的方法。
标签: java