字符串解析到数组的最佳算法

时间:2016-08-18 15:39:15

标签: arrays string algorithm parsing

我有这样的字符串列表。

"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

一个简单的代码示例请了解算法

2 个答案:

答案 0 :(得分: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);
      }
   }
}

答案 1 :(得分: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']})
>>>