【String】 B034 frog count (character count)

1. Title Description

Give you a string croakOfFrogs, which represents a combination of frog sounds (string "croak") from different frogs Since there can be multiple frogs croaking at the same time, multiple "croaks" are mixed in croakOfFrogs. Please return the minimum number of different frogs required for all frogs in the simulated string.

Note: In order to sound the croak "croak", the frog must output the five letters 'c', 'r', 'o', 'a', 'k' in sequence. If all five letters are not output, then it will not sound.

If the string croakOfFrogs is not a mixture of valid "croak" characters, please return -1.

输入:croakOfFrogs = "crcoakroak"
输出:2 
解释:最少需要两只青蛙,“呱呱” 声用黑体标注
第一只青蛙 "crcoakroak"
第二只青蛙 "crcoakroak"

Method 1: Count

  • Because in a legal string, the number of occurrences of each character must be equal.
  • If there is a different character order, and the number is greater than the characters in the earlier relative order, then this string is illegal.
  • When the number of characters is legal, the number of frogs required depends only on the difference between the number of characters c and k.
    • For example: when a frog calls again, while another frog is also calling, then the number of frogs needed at this time will be 2.
public int minNumberOfFrogs(String croakOfFrogs) {
    int[] c = new int[5];
    char[] s = croakOfFrogs.toCharArray();
    int max = 0;
    for (char ch : s) {
        if (ch == 'c') c[0]++;
        if (ch == 'r') c[1]++;
        if (ch == 'o') c[2]++;
        if (ch == 'a') c[3]++;
        if (ch == 'k') c[4]++;
        for (int i = c.length-1; i >= 1; i--) {
            if (c[i] > c[i-1])
                return -1;
        }
        max = Math.max(max, c[0]-c[4]);
    }
    return c[0] == c[4] ? max : -1;
}

Complexity analysis

  • time complexity: O ( n ) O (n)
  • Space complexity: O ( 1 ) O (1)

f w c

Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105617572