Java多数投票法求出现次数大于一半的那个及其次数

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"));
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39455116/article/details/87929951