网上看了一个面试题,感觉挺有意思,试着实现了一下,如下代码
package order;
/**
* @author ty93
* @难度 ***
* @算法: 合并一个字符串中的所有子字符串 例如12342343454565678789->123456789
* 11223344->11223344
* 123423434545656787898901121512->1234567890115
*/
public class StringCombin {
public static String fatherString = "";
public static String getString(String str) {
String stmp = "";
int i;
c: for (i = fatherString.length(); i < str.length(); i++) {
if (fatherString.contains(String.valueOf(str.charAt(i)))) {
int origin = i;
int j;
if (i == str.length() - 1) {
String tempString = str.substring(str.length() - 2);
if (!fatherString.contains(tempString)) {
if (tempString.charAt(0) == tempString.charAt(1)) {
fatherString += tempString.substring(1);
} else {
fatherString += tempString;
}
}
break;
} else if (i == str.length()) {
fatherString += str.substring(str.length() - 1);
break;
}
for (j = origin + 1; j < str.length(); j++) {
String innString = str.substring(origin, j);
if (fatherString.contains(innString)) {
} else {
if (j - origin > 2) {
StringBuffer sb = new StringBuffer(str);
stmp = sb.delete(origin, j - 1).toString();
fatherString = "";
break c;
} else {
stmp = str;
fatherString = fatherString + str.substring(origin, j - 1);
break;
}
}
}
} else {
fatherString = fatherString + String.valueOf(str.charAt(i));
}
}
if (i == str.length()) {
return fatherString;
}
System.out.println(stmp.toString() + "_" + fatherString.toString());
if (stmp != "")
return getString(stmp);
return fatherString;
}
public static void main(String[] args) {
StringBuffer str = new StringBuffer("123423434545656787898901121512");
System.out.println(getString(str.toString()));
}
}