Pyramid Transition Matrix

https://www.lintcode.com/problem/pyramid-transition-matrix/description

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Solution {
    /**
     * @param bottom: a string
     * @param allowed: a list of strings
     * @return: return a boolean
     */
    public boolean pyramidTransition(String bottom, List allowed) {
        // write your code here
        if (bottom.length() < 2) {
            return false;
        }
        Map> dic = new HashMap<>();
        for (int i = 0; i < allowed.size(); i++) {
            String s = allowed.get(i);
            String key = s.substring(0, 2);
            Set list = dic.get(key);
            if (list == null) {
                list = new HashSet<>();
                dic.put(key, list);
            }
            list.add(String.valueOf(s.charAt(2)));
        }
        List last = new ArrayList<>();
        List now = new ArrayList<>();
        last.add(bottom);
        while (true) {
            if (last.isEmpty()) {
                return false;
            }
            now.clear();
            for (int i = 0; i < last.size(); i++) {
                String s = last.get(i);
                if (s.length() == 1) {
                    return true;
                }
                tree(s, now, dic, "");
            }
            List now1 = now;
            now = last;
            last = now1;
        }
    }

    private void tree(String s, List now, Map> dic, String temp) {
        if (s.length() == 1) {
            now.add(temp);
            return;
        }
        String key = s.substring(0, 2);
        Set set = dic.get(key);
        if (set == null) {
            return;
        }
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            tree(s.substring(1), now, dic, temp + next);
        }
    }
}

你可能感兴趣的:(Pyramid Transition Matrix)