对于完全不同的东西,这里有一种方法可以准确地生成所需的字符串,仅此而已。将其视为一个状态机,并使每个状态成为一个函数。非常冗长但直截了当。(如果你做了很多这样的事情,你可以很容易地安排自动生成这个代码。)
因为我们被要求使用 Java,所以这里是 Java。(我还在 Perl 中编写了相同的代码。我只是.=
用chop
字符串代替了StringBuilder
它,它的运行速度比 Java 版本快 3 倍。奇怪。)
import java.io.*;
public class ListAllAlarmedStrings {
static StringBuilder builder;
static int length;
public static void main(String[] args) throws IOException {
length = 5;
if (args.length > 0) {
try {
length = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + " must be an integer");
System.exit(1);
}
}
builder = new StringBuilder(length);
for (int i = 0; i < length; i++)
builder.append("O");
stateA(0, 'A');
stateL(0, 'L');
stateNone(0, 'O');
}
static void stateNone (int pos, char chr) {
if (length < pos + 3)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateNone " + pos + " " +builder.toString());
stateA(pos + 1, 'A');
stateL(pos + 1, 'L');
stateNone(pos + 1, 'O');
}
static void stateL (int pos, char chr) {
if (length < pos + 3)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateL " + pos + " " +builder.toString());
stateA(pos + 1, 'A');
stateLL(pos + 1, 'L');
stateNone(pos + 1, 'O');
}
static void stateLL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateLL " + pos + " " +builder.toString());
stateA(pos + 1, 'A');
stateAlarmed(pos + 1, 'L');
stateNone(pos + 1, 'O');
}
static void stateA (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateA " + pos + " " +builder.toString());
stateAlarmed(pos + 1, 'A');
stateAL(pos + 1, 'L');
stateA(pos + 1, 'O');
}
static void stateAL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateAL " + pos + " " +builder.toString());
stateAlarmed(pos + 1, 'A');
stateALL(pos + 1, 'L');
stateA(pos + 1, 'O');
}
static void stateALL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateALL " + pos + " " +builder.toString());
stateAlarmed(pos + 1, 'A');
stateAlarmed(pos + 1, 'L');
stateA(pos + 1, 'O');
}
static void stateAlarmed (int pos, char chr) {
if (length <= pos)
return;
if (length == pos + 1) {
builder.setCharAt(pos, chr);
System.out.println(builder.toString());
return;
}
builder.setCharAt(pos, chr);
stateAlarmed(pos + 1, 'A');
stateAlarmed(pos + 1, 'L');
stateAlarmed(pos + 1, 'O');
}
}