26进制,字母表示数字,以递归算法升序输出字符串

转载请注明出处:http://blog.csdn.net/jssongwei/article/details/53105502

主要的工具类如下:

/**
 * Created by SongWei on 2016/11/9.
 */
public class Urls {

    public Urls() {}

    public int bigIndex = 0; //字符数组最高位下标
    public char[] urls = {'a' - 1};

    //循环输出num个26进制表示的字符串
    public void generUrls(int num) {

        for (int index = 0; index < num; index++) {//从'a'开始一直生成num个url
            if (urls[0] < 'z') {
                urls[0] = (char) (urls[0] + 1);
                myPrint(urls);//打印urls内容
                continue;
            } else {
                //准备递归处理进位问题
                carry2Forward(1);
            }
        }
    }

    //向前进一位
    private void carry2Forward(int carry2Index) {// 只有1个元素
        urls[carry2Index - 1] = 'a';

        if (carry2Index <= bigIndex) {//该位未超出最大下标
            if (urls[carry2Index] < 'z') {
                urls[carry2Index] = (char) ((int) urls[carry2Index] + 1);
                myPrint(urls);//打印urls内容
            } else {
                urls[carry2Index] = 'a';
                carry2Forward(++carry2Index);//向高一位进位
            }
        } else {
            carry2Head();//最高位加一个'a'
            myPrint(urls);//打印urls内容
        }
    }

    //进位到最前面,新增一最高位:urls最高位新加'a'
    private void carry2Head() {
        char[] newUrls = new char[bigIndex + 2];
        for (int i = 0; i <= bigIndex; i++) {
            newUrls[i] = urls[i];
        }
        bigIndex++;
        newUrls[bigIndex] = 'a';
        urls = newUrls;
    }

    //逆序打印结果(为计算方便,在char[]数组中设计成前面是低位,后面是高位)
    private void myPrint(char[] chars) {
        for (int i = chars.length - 1; i >= 0; i--) {
            System.out.print(chars[i]);
        }
        System.out.print("\n");
    }
}

主方法如下,打印50个:

public class Main {
    public static void main(String[] args) {
        Urls urls = new Urls();
        urls.generUrls(50);
    }
}

最终打印出来的结果如下:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
an
ao
ap
aq
ar
as
at
au
av
aw
ax
ay
az
ba
bb
bc
bd
be
bf
bg
bh
bi
bj
bk
bl
bm
bn
bo
bp
bq
br
bs
bt
bu
bv
bw
bx
by
bz
ca
cb
cc
cd
ce
cf
cg
ch
ci
cj
ck
cl
cm
cn
co
cp
cq
cr
cs
ct
cu
cv

点赞