/**
* 从一个字符串中取出首位相同但内部字符都最多只能出现一个的最长子字符串 第一层:从左边第一个字符开始遍历字符串,截取与这个字符可以组成首位相同的子字符串
* 第二层:将截取的首尾相同的字符串的首尾字符去掉,再次进入第一层的验证,如果内部没有相同字符了,就返回去掉首尾字符之前的字符串(只有在长度大于),如果有,继续重复第二层验证
*
* @author jiang
*/
public class StringSplit {
// 传入一个字符串,获取其中的首尾相同的字符串
String split(String str) {
// 默认值为null表示如果str中没有一个首尾相同的子字符串,则返回null
String result = "";
for (int i = 0; i < str.length() - 1; i++) {
char a = str.charAt(i);
int index2 = str.indexOf(a, i + 1);
if (index2 == -1) {// 如果后面没有第二个a代表的字符了
continue;// 继续看下一个位置的字符
} else {// 后面有第二个a字符
String s = str.substring(i, index2 + 1);// 截取出这个首位字母相同的字符串
System.out.println("s->" + s);
String child = splitChild(s);// 递归得到s的最简字符串,有可能是s本身
System.out.println("child->" + child);
if (child.length() > result.length()) {// 如果这个最简字符串的长度大于原本用于返回的字符串
result = child;// 就把返回的字符串变为这个最简子字符串
}
}
}
return result;
}
// 传入一个首尾字符相同的字符串,判断里面是否还有首尾相同的子字符串
String splitChild(String str) {
String result = str;// 默认值为str,表示如果str里没有其他首尾相同的子字符串,则返回它本身
// 截取出第二个字符为首位,倒数第二个字符为末尾的字符串
String s = str.substring(1, str.length() - 1);
// 判断这个字符串内是否有首尾相同的子字符串
String s1 = split(s);
if (s1 == "") {
return result;
} else {
return s1;
}
}
public static void main(String[] args) {
String s = "9qwertytuiopasdfgghjkl99asdfghjtfba121sdsaefva121asdfghjkl1";
System.out.println(new StringSplit().split(s));
}
}