卡的说法凉快圣诞节

package com.nphyez.basic.algorithm;

import java.util.*;

public class MaximumLengthOfConcatenatedStringWithUniqueCharacters {

public static void main(String[] args) {

// String[] origin = {“yy”, “bkhwmpbiisbldzknpm”};
// String[] origin = {“abc”, “bc”, “ac”};
String[] origin = {“a”, “abc”, “d”, “de”, “def”};
List input = new ArrayList<>(Arrays.asList(origin));
System.out.println(new Solution().maxLength(input));
}

public static class Solution {
    List searched = new ArrayList<>();
    String tempResult = "";
    Map valued = null;

    public int maxLength(List arr) {
        valued = stringValued(arr);
        LinkedList results = new LinkedList<>();

        arr.forEach(item -> {
            searched.clear();
            tempResult = "";
            if (hasDuplicate(item)) {
                return;
            }
            searchNext(item);
            results.add(tempResult);
        });

        if (results.size() > 1) {
            Collections.sort(results, (o1, o2) -> o1.length() > o2.length() ? -1 : (o1.length() < o2.length() ? 1 : 0));
        }
        return results.size() == 0 ? 0 : results.get(0).length();
    }

    public void searchNext(String current) {
        Stack myStack = new Stack<>();
        myStack.push(current);
        while (!myStack.isEmpty()) {
            String cur = myStack.pop();
            searched.add(cur);
            tempResult += cur;
            for (String key : valued.keySet()) {
                if (!searched.contains(key) && (stringValuing(tempResult) & valued.get(key)) == 0) {
                    myStack.push(key);
                }
            }
            
        }

    }

    public Map stringValued(List arr) {
        Map mapped = new HashMap<>();
        arr.forEach(str -> {
            mapped.putIfAbsent(str, stringValuing(str));
        });
        return mapped;
    }

    public int stringValuing(String str) {
        int result = 0;
        for (char ch : str.toCharArray()) {
            int cur = (int) Math.pow(2, ch - 97);
            result |= cur;
        }
        return result;
    }

    public boolean hasDuplicate(String str) {
        String result = "";
        for (char ch : str.toCharArray()) {
            if (result.contains(String.valueOf(ch))) {
                return true;
            }
            result += ch;
        }
        return false;
    }
}

}

你可能感兴趣的:(卡的说法凉快圣诞节)