- package text;
- public class Text23 {
- /**
- * 已知两个字符串,String a = "abcdefghijklmnopqrstuvwxyz";String b="1234567890abcdfrgtddd12321414";
- * 编写代码求出这两个字符串中最大公共字符串(最大公共字符串:
- * 比如 “abc123edf”和"bc123jg"的最大公共字符串是“bc123”)。上传代码的时候将运算结果截图一起提交。
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String a = "abcdefghijklmnopqrstuvwxyz";
- String b = "1234567890abcdfrgtddd12321414";
-
- String result = getString(a, b);
- System.out.println(result);
-
- }
- //获得最大子串
- private static String getString(String a, String b) {
- String maxStr = null;
- String minStr = null;
- maxStr = (a.length() > b.length())? a : b;//获取最大的字符串
- minStr = maxStr.equals(a) ? b : a;//获取最小的字符串
- for (int i = 0; i < minStr.length(); i++) {
- for (int start = 0, end = minStr.length() - i; end != minStr.length() + 1; start++, end++) {
- String sub = minStr.substring(start, end);
- if (maxStr.contains(sub))//如包含则返回最大子串
- return sub;
- }
- }
- return null;
- }
-
- }
复制代码
赞一个! |