用1、2、2、3、4、5这六个数字打印(算法)

1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、412345等. 
要求:”4”不能在第三位,”3”与”5”不能相连。


    private static boolean isValidNumber(String str) {

       String[] listNumber = new String[] { "1", "2", "3", "4", "5" };
        // 检查是否包含12345这五个数,不包含返回false
        for (String number : listNumber ) {
            if (str.indexOf(number) < 0)
                return false;
        }
        // 检查有几个2,只有一个或者大于两个返回false
       int i,index=-1,count=0;

       for(i=0; i<str.length;i++){

           if(str.indexof("2",index+1)!=-1){

             index=str.indexof("2",index+1);

             count++;

            }

        }

   if(count!=2){

        return false;}


        // 检查4在不在第三位,是返回false
        if (str.charAt(2) == '4') {
            return false;
        }
        // 检查是否存在35在一起,有返回false
        if (str.indexOf("35") >= 0 || str.indexOf("53") >= 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int count=0;
        for (int i = 122345; i <=543221; i++) {
            if (isValidNumber(String.valueOf(i))) {
                System.out.println(i);
                count++;
            }
        }
        System.out.println(count);
    }

-------知识点:

indexOf()的用途:用于字符串中子串的查找
indexOf()的用法:返回字符中indexof(string)中字串string在父串中首次出现的位置,从0开始,没有返回-1。
语法
stringObject.indexOf(searchvalue,fromindex)

searchvalue  为必需,规定需检索的字符串值;

fromindex  为可选的整数参数。规定在字符串中开始检索的位置。如省略该参数,则将从字符串的首字符开始检索。

说明
该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

charAt()此方法返回位于字符串的指定索引处的字符。该字符串的索引从零开始。

语法
此方法定义的语法如下:

public char charAt(int index)
参数
这里是参数的细节:

index -- 返回字符的索引。

返回值
该方法的返回指定索引处char值。

猜你喜欢

转载自blog.csdn.net/sunstar8921/article/details/81201660