字符串中出现的相同且长度最长的字符串

来源:互联网 发布:java覆盖父类方法 编辑:程序博客网 时间:2024/06/04 18:21
package com.a.b;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class StringAnalysis {public static void main(String[] args) {String s = null;// "   ";// " bcbccccc";// null;//"yyabcdabjcabceg";find(s);}private static String commonStart(String thisOne, String another) {int length1 = thisOne.length();int length2 = another.length();int j = 0;for (; j < length1 && j < length2&& (thisOne.charAt(j) == another.charAt(j)); j++) {}return thisOne.substring(0, j);}private static void find(String s) {if (null == s) {System.out.println("s==null");return;}int length = s.length();List<String> list = new ArrayList<String>();for (int i = 0; i < length; i++) {list.add(s.substring(i));}Collections.sort(list);int max = 0;int maxIndex = -1;for (int i = 0; i < length - 1; i++) {String node = list.get(i);String next = list.get(i + 1);String common = commonStart(node, next);if (common.length() > max) {max = common.length();maxIndex = i;}}if (maxIndex >= 0) {String common = list.get(maxIndex).substring(0, max);System.out.println(common + "#" + (s.indexOf(common) + 1));} else {System.out.println("not found.");}}}

0 0
原创粉丝点击