{1:A}
{2:B} {1:A,C}
{1:C} 转变成 {2:B,G}
{3:D} ===========> {3:D,F,H}
{4:E} {4:E}
{3:F}
{2:G}
{3:H}
====================================================================================================================================
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
public class lzwCode {
public static void main(String [] args) {
codeTest();
}
public static void codeTest() {
String str[] = {"1:A", "2:B", "1:C", "3:D", "4:E", "3:F", "3:H", "2:G"};
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
for (int i=0; i<str.length; i++) {
int key = Integer.parseInt(str[i].split(":")[0]);
String tmp = str[i].split(":")[1];
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<String>();
}
list.add(tmp);
map.put(key, list);
}
System.out.println(map.toString());
}
}
控制台结果如下:
PHP实现该功能:
<?php
function lzwCode() {
$strArr = array("1:A", "2:B", "1:C", "3:D", "4:E", "3:F", "3:H", "2:G");
$arrayTemp = array();
foreach ($strArr as $value) {
$strTemp = explode(":", $value);
$key = $strTemp[0];
$val = $strTemp[1];
if (array_key_exists($key, $arrayTemp)) {
$arrayTemp[$key] = $arrayTemp[$key].",".$val;
} else {
$arrayTemp[$key] = $val;
}
}
return $arrayTemp;
}
print_r(lzwCode());
?>
结果如下: