0

有人可以帮我实现这个吗?我正在尝试以递归方式执行此操作,但我真的很头疼。我想在需要时以模式的形式生成一个字符串。前任。

a A b B ... z Z aa aA Aa AA bb bB Bb BB ...

我目前正在尝试这个

static int count;//a = 97, z = 122...A = 65, Z = 90
static int length = 1;
static boolean upper;

public static void main(String args[]){
    for (int i = 0; i < 10; i++){
        System.out.println(nextString(length));
    }
}

static String nextString(int len){
    char ch = (char) ((len == length ? count++ : count) / 26 + 97);
    if (upper)
        ch -= 32;
    upper = !upper;
    String s0 = String.valueOf(ch);
    if (len != 1)
        s0 = s0.concat(nextString(len - 1));
    return s0;
}
4

1 回答 1

2

我不确定,如果我理解这个问题,但这里有一段代码,应该会生成所需的模式。

public class CharPatternGenerator {

private int length; //length of current "word"
private char letter;//letter used in current "word"
private int number; //number converted to binary and replaced with letters
                    //for example: 5 in binary is 101, in letters: AaA

public CharPatternGenerator() {
    this.length = 1;    
    this.letter = 'a';  
    this.number = 0;    
}

public String nextString(int len){
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < len; i++)
        result.append(nextWord()).append(' ');

    return result.substring(0, result.length() - 1);

}

private String nextWord() {
    StringBuilder word = new StringBuilder();
    int numberCopy = number;

    /*following loop converts number to binary representation
     * with all 1s replaced with capital case 
     * and 0s - with lower case 
     */
    for (int i = 0; i < length; i++) {
        if (numberCopy % 2 == 0)
            word.append(letter);
        else
            word.append((char) (letter - 32));
        numberCopy /= 2;
    }
    String result = word.reverse().toString();

    number++;
    if (number >= Math.pow(2, length)) {
        number = 0;
        letter++;
        if (letter > 'z') {
            letter = 'a';
            length++;
        }
    }

    return result;

}

/*
 * example of use
 */
public static void main(String[] args) {
    CharPatternGenerator generator = new CharPatternGenerator();
    System.out.println(generator.nextString(100));
    System.out.println(generator.nextString(100));
}
}
于 2013-08-01T23:28:57.733 回答