算法程序题:
该公司笔试题就1个,要求在10分钟内作完。
题目如下:用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
现在把两种解法公布于下:
方法一:
private static String[] forbidenNumber = new String[] { "0", "6", "7", "8", "9" }; private static String[] mustExistNumber = new String[] { "1", "2", "2", "3", "4", "5" }; private static boolean isValidNumber(String str) { // 检查是否有非法数字,有返回false,否则继续 for (String number : forbidenNumber) { if (str.indexOf(number) >= 0) { return false; } } // 检查是否存在要的数字,如果不存在返回false,否则继续 for (String number : mustExistNumber) { int temp = str.indexOf(number); if (temp < 0) { return false; } else if ((str.indexOf(number, temp + 1) > temp) && str.charAt(temp) != '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) { // TODO code application logic here for (int i = 122345; i < 543221; i++) { if (isValidNumber(String.valueOf(i))) { System.out.println(i); } } }
private static String[] mustExistNumber = new String[] { "1", "2", "2", "3", "4", "5" }; private static boolean isValidNumber(String str) { // 检查是否包含12345这五个数,不包含返回false for (String number : mustExistNumber) { if (str.indexOf(number) < 0) return false; } // 检查是否有两个2,只有一个返回false if (str.lastIndexOf("2") == str.indexOf("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) { // TODO code application logic here for (int i = 122345; i < 543221; i++) { if (isValidNumber(String.valueOf(i))) { System.out.println(i); } } }