在一个队列destQ中,从前向后搜索是否有字符串flag,下面是算法实现以及测试程序。回溯功能暂未实现。
private int findFlag( final LinkedBlockingQueue
final String flag) {
byte [] flagArr = flag.getBytes();
Byte[] destArr = destQ.toArray( new Byte[0]);
int matchCount = 0; // 已匹配的字节数
int flagPos = -1; // 标志末尾的编号
int i = 0;
int backupIndex = 0; // 用于回溯的索引
while (i <= destQ.size()) {
if (flag.length() <= matchCount) {
flagPos = i;
break ;
} else {
if (destArr[i] == flagArr[matchCount]) {
matchCount++;
} else {
matchCount = 0;
// i = backupIndex;
}
}
i = i + 1;
if (matchCount == 1) {
backupIndex = i;
}
}
return flagPos;
}
@Test
public void runFindFlag() {
LinkedBlockingQueue
for ( int i = 33; i < 123; i++) {
analyzerBuffer.offer( new Byte(( byte ) i));
}
String endFlag = "123" ;
int endFlagPos = findFlag(analyzerBuffer, endFlag);
List
analyzerBuffer.drainTo(cmplXmlStr, endFlagPos);
System. out .println(cmplXmlStr);
}