您的位置:首页 > Web前端

String 常用方法最优算法实现总结 (三) -- findCommonSubstring 和difference

2015-06-29 16:37 399 查看
1. String difference(final String str1, final String str2)

说明:Compares two Strings, and returns the portion where they differ.

i.e:

("ahc", "bcu") -> "ahbu"

/**
*
* @Title: difference
* @Description: Compares two Strings, and returns the portion where they differ.
* @param str1 input string1
* @param str2 input string2
* @return return the difference characters, keep the original sequence
*/
public static String difference(final String str1, final String str2) {
if (null == str1 || null == str2) {
return str1 == str2 ? null : (str1 == null ? str2 : str1);
}

if (str1.equals(str2)) {
return "";
} else {
String newStr = removeDuplicated(false, str1, str2);
String duplicated = findDuplicated(newStr);
final int length = duplicated.length();

if (length == 0) {
return newStr;
} else {
String rs = removeDuplicated(true, duplicated, newStr);
return new String(rs.toCharArray(), length, rs.length() - length);
}
}
}


2. List<String> findCommonSubstring(String...str)

说明:Returns the first longest substring from Strings.

i.e:

({"ahcdx", "bcuycd", "cejcdm"}) -> "cd"

/**
*
* @Title: findCommonSubstring
* @Description: Returns the first longest substring from Strings.
*
* @param strArr input string array
* @return the repeated Stringc
*/
public static List<String> findCommonSubstring(String... strArr) {
/* initial check */
if (strArr == null || strArr.length == 0) {
return null;
} else if (strArr.length == 1) {
return Arrays.asList(strArr);
}

/* check the first element */
if (isEmpty(strArr[0])) {
return null;
}

int smallLen = strArr[0].length();
int index = 0;
int len = strArr.length;

/* identify smallest String */
for (int i = 1; i < len; i++) {
/* if contains empty, returns directly */
if (isEmpty(strArr[i])) {
return null;
}

if (smallLen > strArr[i].length()) {
smallLen = strArr[i].length();
index = i;
}
}

String smallStr = strArr[index];
List<String> list = new ArrayList<String>();
int step = 1;

/* outer loop smallest string */
for (int i = 0; i < smallLen; i++) {
boolean isPass = true;

/* inner loop smallest string */
for (int j = i + step; j <= smallLen; j++) {
String tempCom = smallStr.substring(i, j);

/*
* loop and judge whether temp string is contained in other strings
*/
for (int k = 0; k < len; k++) {
if (k != index && !strArr[k].contains(tempCom)) {
isPass = false;
break;
}
}

/* if not contained, terminal the loop */
if (!isPass) {
break;
}

if (list.isEmpty()) {
list.add(tempCom);
} else {
int maxLen = list.get(0).length();
step = j - i;

/* if existing longer string, clear the list */
if (maxLen < step) {
list.clear();
}

/* if existing same and longer string, add it to list */
if (maxLen <= step && !list.contains(tempCom)) {
list.add(tempCom);
}
}
}
}

return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: