Java多数投票法 package likou; public class Toupiao { public static int getVal(String str) { int count = 0;//用于判断相邻两个数是否相同 char now = str.charAt(0);//用于记录多数的那个数 for (int i = 0; i < str.length(); i++) { if (count == 0) { now = str.charAt(i); count += 1; } else { if (now == str.charAt(i)) { count += 1; } else { count -= 1; } } } //循环结束now就是所求的多数 int countNum = 0;//多数出现的次数 for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == now) { countNum++; } } return countNum; } public static void main(String[] args) { System.out.println(getVal("AAAAAAAAAABBBBBBBBB")); } }