1,写出一个函数,比较两个字符串,返回最大公串,例如abacdaccbadc和cedaccbe返回daccb;2,有100个数字,其中有正数也有负数,找出连续三个相加之和最大部分;要求:尽量不要使用库函数!两道一起来:支持搜索中文,import java.util.Random;public class Test{ private static int maxSubStart = 0; private static int maxSubLength = 0; private static char[] c1, c2; private static boolean isSame(int i, int j) { return c1[i] == c2[j]; } private static void setMaxSub(int start1, int start2) { int i = start1, j = start2; int maxStart = 0; int maxLength = 0; for (; i < c1.length && j < c2.length; i++,j++) { if (isSame(i, j)) { maxLength++; } else break; } if (maxLength > maxSubLength) { maxSubLength = maxLength; maxSubStart = start1; } } private static String getMaxCommonString(String s1, String s2) { c1 = s1.toCharArray(); c2 = s2.toCharArray(); if (c1.length > c2.length) // swap s1, s2 so s1.length < s2.length { char[] c = c1; c1 = c2; c2 = c; } int minLength = c1.length; int maxLength = c2.length; for (int i = 0; i < minLength; i++) { char ch = c1[i]; for (int j = 0; j < maxLength; j++) { if (ch == c2[j]) { setMaxSub(i, j); } } } return new String(c1, maxSubStart, maxSubLength); } private static int[] getRandomInt(int length) { Random r = new Random(); int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = r.nextInt(200) - 100; } return res; } private static int count(int[] num, int i) { return num[i]+num[i+1]+num[i+2]; } private static int getMaxThreeStart(int[] num) { int end = num.length - 3; int max = 0; int start = 0; for (int i = 0; i < end; i++) { int c = count(num, i); if (c > max) { max = c; start = i; } } return start; } public static void main(String[] args) { //abacdaccbadc和cedaccbe String s1 = "abacd测试汉字 accbadc", s2 = "ced测试汉字 accbe"; System.out.println(s1 + " " + s2 + " 的最大公串为: " + getMaxCommonString(s1, s2)); int[] num = getRandomInt(100); int start = getMaxThreeStart(num); for (int i = 0; i < 100; i++) { System.out.print(num[i] + " "); if (i%10 == 9) { System.out.println(); } } System.out.println("三个连续数字之和最大的三个数子为: " + num[start] + " " + num[start+1] + " " + num[start+2]); }};
新闻热点
疑难解答