中级农民
- 积分
- 112
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-11-23
- 最后登录
- 1970-1-1
|
尝试着写了一个 但是不能handle duplicate, 如果handle duplicate 改动应该也不大- public static List<String> partitionStr(String[] strs) {
- Arrays.sort(strs, (String a, String b) -> a.length() - b.length());
- Map<String, Set<String>> parentStr = new HashMap<>();
- for (int i = 0; i < strs.length; i++) {
- for (int j = i + 1; j < strs.length; j++) {
- if (strs[j].indexOf(strs[i]) == -1) {
- continue;
- }
- Set<String> s = parentStr.getOrDefault(strs[i], new HashSet<>());
- s.add(strs[j]);
- parentStr.put(strs[i], s);
- }
- }
-
- List<String> res = new ArrayList<>();
- Set<String> visited = new HashSet<>();
- for (int i = 0; i < strs.length; i++) {
- if (parentStr.containsKey(strs[i])) {
- for (String val: parentStr.get(strs[i])) {
- if (parentStr.containsKey(val)) {
- parentStr.put(strs[i], nonIntersect(parentStr.get(strs[i]), parentStr.get(val)));
- }
- }
- }
- }
- for (int i = 0; i < strs.length; i++) {
- if (!parentStr.containsKey(strs[i])) {
- continue;
- }
- path(parentStr, res, "", visited, strs[i]);
- }
- return res;
- }
-
- public static void path(Map<String, Set<String>> map, List<String> res, String cur,
- Set<String> visitedKey, String key) {
- if (visitedKey.contains(key)) {
- return;
- }
- if (map.containsKey(key)) {
- for (String val: map.get(key)) {
- path(map, res, cur + key + " ", visitedKey, val);
- }
- visitedKey.add(key);
- } else {
- res.add(cur + key);
- return;
- }
- }
-
- public static Set<String> nonIntersect(Set<String> a1, Set<String> a2) {
- Set<String> res = new HashSet<>();
- for (String val: a1) {
- if (!a2.contains(val)) {
- res.add(val);
- }
- }
- return res;
- }
复制代码 |
|