按照單詞的字母是否相同對字符串數組進行分組

今天收到一個面試題:給了一個數組(如: ["cars", "thing", "scar", "dog", "god", "arcs", "the"]),需要把由顛倒字母順序組成的單詞放到同一個數組(生成後的結果:[["cars", "scar", "arcs"], ["thing"], ["dog", "god"], ["the"]]


我是這麼實現的:

package com.mingyisoft.bean.test;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.ArrayUtils;
public class SameWordUtile {
/**
 * 比較兩個字符串組成是否相同
 * 
 * @param sourceStr 
 * @param targetStr
 * @return
 */
public static boolean checkSimilarDegree(String sourceStr, String targetStr) {
boolean checkResult = false;
if (sourceStr.length() == targetStr.length()) {
char[] sourceStrCharArray = sourceStr.toCharArray();
char[] targetStrCharArray = targetStr.toCharArray();
int n = targetStrCharArray.length;
for (int i = 0; i < n; i++) {
checkResult = false;
for (int j = 0; j < sourceStrCharArray.length; j++) {
if (targetStrCharArray[i] == sourceStrCharArray[j]) {
// 從數組中刪除已經比較相同的
sourceStrCharArray = ArrayUtils.remove(
sourceStrCharArray, j);
checkResult = true;
break;
}
}
}
}
return checkResult;
}
/**
 * 分組處理
 * @param sourceArray
 * @return
 */
public static Object[] classify(String[] sourceArray) {
// 獲取數組的個數
int sourceArrayLength = sourceArray.length;
// 聲明臨時的Map,用來存放生成後的數組。
Map<String, String[]> tempMap = new HashMap<String, String[]>();
boolean hasSame = false;
for (int i = 0; i < sourceArrayLength; i++) {
hasSame = false;
if (i == 0) {
// 如果是數組的第一個字符串,則初始化Map的值
tempMap.put(sourceArray[i], new String[] { sourceArray[0] });
} else {// 不是第一個數組的話,則開始比較
Set<Entry<String, String[]>> entrySet = tempMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
String keyString = entry.getKey();
// 判斷是否已經存在相似的
if (checkSimilarDegree(keyString, sourceArray[i])) {
// 存在相似的,則把相似的放到對應的數組裏面
entry.setValue(ArrayUtils.add(tempMap.get(keyString),
sourceArray[i]));
hasSame = true;
break;
}
}
if (!hasSame) {
// 不存在相似的,新建一個key-value,key使用該數組的字符串,value採用新建的數組(包含該字符串)
tempMap.put(sourceArray[i], new String[] { sourceArray[i] });
}
}
}
return  tempMap.values().toArray();
}
public static void main(String[] args) {
String[] sourceArray = new String[] { "cars", "thing", "scar", "dog",
"god", "arcs", "the","het" };
Object[] targetObjectArr = classify(sourceArray);
for(Object tempObj:targetObjectArr){
String[] ss = (String[]) tempObj;
System.out.println(ArrayUtils.toString(ss));
}
}
}


注:面試結果是算法太複雜,應該比這還高效的算法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章