求一个字符串中出现次数最多的字符的高效算法

/** * 求一个字符串中出现次数最多次数的字符 * @author 懒人-小何 * */ public class StringTest { public static void main(String[] args) { int[] num = new int[123]; //用来记录每个字符出现的次数 String str = "abzbbzcczzzwwaaasazzasdafccsddvvvbbbdaiizolyyqppachhcushuihyqppachhcushuihyqppachhcushuihyqppachhcushuih" + "yqppachhcushuihyqppachhcushuihyqppachhcushuihyqppachhcushuihyqppachhcushuih" + "yqppachhcushuihyqppachhcushuihyqppachhcushuihyqppachhcushuihyqppachhcushuih" + "yqppachhcushuihyqppachhcushuihyqppachhcushuih" + "yqppachhcushuih" + "yqppachhcushuih" + "afasfsafasfdfaaloxhhhoxpppqpzzyyvnammdmdmdmmamdmamdamdmdmdmmamdmamdamdmdmdmmamdmamdamdmdmdmmamdmamdamd" + "mdmdmmamdhhhhhhhhhhhhhhhhhhhhhhhhmamdamd" + "mdmdmmamdmahhhhhhhhhhhhhhhhhhhhhhmdamd" + "uayytzcwqaoiohhhhhhhhhhhhhhhhmmmmmmmmmmhhhhmmmmmmmhhhmmmmmmmmmmmmmmmdadadadammmmmmmm" + "damdamdmamdamdmamdmamdammdamdmmdmamdmamdmamdmamdma" + "mdamdmamdamdmamdmamdmamdmamdamdmamdmadma" + "h" + "adadaweqeqhwuhedihhhhhhhhhhhhhhhwadhwqgduawgduawgudaysudg" + "afawsdhsiahdiashdsahd" + "fhashfuisahfuiahuhhhhhhhhhhhhfh" + "'afhuahfhhhhhhhisahfuia" + "afashifhsaufhiqwye7qeqw7ewdhhhaigsdiagdisafgasufisafagdaugdugauyd" + "dasufgasugdusghhhhhhhhhhhhhhhhhha7q7eguwqgeqgdiagdiagdiagduaoqyhweq" + "hhhhh" + "daifhahdaghf7ahhhhhhhhhhhhhhwyf7adihdadoadoahdoahdiwhqehqw" + "hhhhhhhh" + "mamiahhhhhhhsdbcsagfagdsdiahduiahdizzzzz"; for (int i = 1; i <= 10; ++i) { str += str; } int max = Integer.MIN_VALUE; char c = ' '; for (int i = 0; i < str.length(); ++i) { int index = (int) str.charAt(i); if (++num[index] > max) { max = num[index]; c = str.charAt(i); } } System.out.println("max = " + max + " c = " + c); } }

你可能感兴趣的:(算法)