2016-08-18 30 views
0

我有像這樣的字符串列表。字符串解析到數組的最佳算法

"Section 1/Part 1" 
"Section 2/Part 1" 
"Section 2/Part 2" 
"Section 3/Part 1" 
"Section 3/Part 2" 
"Section 3/Part 3" 

我要分析它的數組列表中的數組列表如下:

Section 1 -> Part 1 
Section 2 -> Part 1 
      -> Part 2 
Section 3 -> Part 1 
      -> Part 2 
      -> Part 3 

一個簡單的代碼示例,請於理解算法

+0

用'/'分割,然後根據第一項進行分類。你的編程語言是什麼? – Kasramvd

+0

我已經把它分開了。我想用它創建數組 –

+0

你嘗試了什麼? – Winter

回答

3

這是java的解決方案:

import java.util.*; 

public class a { 
    public static void main(String[] args) { 
     List<String> input = new ArrayList<String>(); 
     input.add("Section 1/Part 1"); 
     input.add("Section 1/Part 2"); 
     input.add("Section 2/Part 1"); 
     // ... 

     HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); 

     for (String s : input) { 
     String[] parts = s.split("/"); 
     String key = parts[0]; 
     String value = parts[1]; 

     ArrayList<String> list = map.get(key); 
     if (list == null) { 
      list = new ArrayList<String>(); 
      map.put(key, list); 
     } 

     list.add(value); 
     } 
    } 
} 
+0

謝謝兄弟:) –

2

這裏是Python中的方法,該方法將它們存儲在詞典:

>>> from collections import defaultdict 
>>> d = defaultdict(list) 
>>> 
>>> for sec, part in [i.split('/') for i in arr]: 
...  d[sec].append(part) 
... 
>>> 
>>> d 
defaultdict(<type 'list'>, {'Section 1': ['Part 1'], 
          'Section 2': ['Part 1', 'Part 2'], 
          'Section 3': ['Part 1', 'Part 2', 'Part 3']}) 
>>> 
+0

謝謝你的回答。你能用Java寫這個嗎? –