public class CountGeese {
/**
* 计算大雁的数量
* 根据输入的声音字符串,判断并计算发出完整"quack"叫声的鹅的数量
* 如果声音字符串能够合理地表示至少一只大雁完整地叫了"quack",则返回鹅的数量;否则返回-1
*
* @param sounds 包含鹅叫声的字符串
* @return 完整叫声的大雁的数量,如果没有完整的叫声则返回-1
*/
public static int countGeese(String sounds) {
//记录叫声的数组count,和叫声代表的字符串
String quack = "quack";
int[] count = new int[quack.length()];
//遍历输入的字符串字符
for (int i = 0; i < sounds.length(); i++) {
char ch = sounds.charAt(i);
//获取该字符在叫声字符串中的位置
int place = quack.indexOf(ch);
//不在叫声中则返回-1
if (place == -1) {
System.out.println(-1);
System.exit(0);
} else if (place == 0) {
//如果是叫声的开头第一个字符‘q',分析有没有空闲的大雁能叫
if (count[quack.length() - 1] > 0) {
//有空闲的大雁,就减少叫到'k'位置的大雁数量
count[quack.length() - 1]--;
}
//无论有没有,都增加叫到'q'的大雁
//(没有是新增加大雁)(有是将叫到'k'的大雁移到'q'
count[place]++;
} else if (count[place - 1] > 0) {
//叫其他字符时,需要从该字符在叫声中的前一个字符移到该字符
//所以需要将叫前一个字符的大雁数量减一,叫该字符的数量加一
count[place - 1]--;
count[place]++;
}
//如果叫的字符没有前一个字符可以移,说明无法构成完整的叫声,不用处理
//继续处理后面的叫声字符
}
int res = count[quack.length() - 1];
//输出结果,没有完整的大雁叫声输出-1;
//有则输出大雁数量
if (res == 0) {
return -1;
} else {
return res;
}
}
public static void main(String[] args) {
String sounds = "quackquackquack";
System.out.println("最少由 " + countGeese(sounds) + " 只大雁发出叫声。");
}
}