改进版,数字不能重复
- public class Test6 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //正则表达式,代表不以4开头的字符串
- String regex1 = "^[^4].*$";
-
- //代表1和3相连的字符串
- String regex2 = ".*[1][3].*$";
- String regex3 = ".*[3][1].*$";
- //建立存储组合的字符
- StringBuilder sb = new StringBuilder("");
- String str = null;
- int count = 0;//统计个数
-
- for(int i = 1;i < 5;i++){
- for (int j = 1 ; j < 5; j++) {
- for(int k = 1; k < 5 ; k++){
- for(int h = 1 ; h < 5 ; h++){
- sb.append(i).append(j).append(k).append(h);
- str = sb.toString();
- if(str.matches(regex1))//不以4开头
- {
- if(!(str.matches(regex2)||str.matches(regex3))){//1和3不相连
- if(single(str)){ //过滤,只要数字不重复的组合
- count++;
- System.out.println(str+"..."+count);
- }
- }
- }
- sb.delete(0,sb.length());
- }
- }
- }
- }
- }
- private static boolean single(String str) { //去除相同数字
- // TODO Auto-generated method stub
- boolean flag = true;
- for(int i = 1;i < 5;i++){
- int count = 0;
- int offset = 0;
- while((offset = str.indexOf(String.valueOf(i),offset))!=-1){
- offset += 1;
- count++;
- if(count > 1){
- flag = false;
- break;
- }
- }
- }
- return flag;
- }
- }
复制代码 |