/**
* 题目描述:
*
* 一群大雁往南飞,给定一个字符串记录地面上的游客听到的大雁叫声,请给出叫声最少由几只大雁发出。具体的
*
* 1.大雅发出的完整叫声为”quack“,因为有多只大雁同一时间嘎嘎作响,所以字符串中可能会混合多个”quack”
*
* 2.大雁会依次完整发出”quack”,即字符串中'q,u,a,c,k这5个字母按顺序完整存
*
* 在才能计数为一只大雁如果不完整或者没有按顺序则不予计数。
*
* 3.如果字符串不是由'q,u',a',c,k字符组合而成,或者没有找到一只大雁,请返回-1.
*/
用例:
输入->输出
quackquack--> 1
qaauucqckk--> -1
quacqkuac --> 1
qququaauqccauqkkcauqqkcauqqkcaaukccakkkck --> 5
quackqquackuackqqqqquack --> 2
package niuke;
/**
* @Author tzccc
* @Date 2023/8/9
*/
public class dayan {
public static void main(String[] args) {
String str = "qaauucqckk";
node q = new node('q');
node u = new node('u');
node a = new node('a');
node c = new node('c');
node k = new node('k');
q.next = u;
u.next = a;
a.next = c;
c.next = k;
k.next = q;
System.out.println(count(str,q) == 0 ? -1 : count(str,q));
}
static int count(String str,node root){
if (str.length()<5){
return 0;
}
node q = root;
boolean flag = false;
int len = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == q.flag){
len++;
q = q.next;
}
if (len==5){
flag = true;
i = i - 4;
len = 0;
for (int j = 0; j < 5; j++) {
str = str.replaceFirst(String.valueOf(q.flag),"");
q=q.next;
}
}
}
if (!flag){
return 0;
}
return count(str,root) + (flag ? 1 : 0);
}
static class node{
public char flag;
public node next;
public node(char flag){
this.flag = flag;
}
}
}
暴力解法