package cn.exploring.engine.server.db.util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 将驼峰式的字符串转换成 _ 分隔的字符串
     * @param aa
     * @return
     */
    public static String humpToLine2(String aa) {
        Matcher matcher = humpPattern.matcher(aa);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 将字典中的以"_"切分的Key，转换成驼峰式命名。
     * @param rawMap
     * @return
     */
    public static Map<String, Object> exchangeMapKeyName(Map<String, Object> rawMap){
        Map target = new HashMap();
        for (String mapKey: rawMap.keySet()){
            target.put(exchangeStringToHump(mapKey), rawMap.get(mapKey));
        }
        return target;
    }



    /**
     * 将以_分割的字符串，转成驼峰式命名的字符串,获取到的sql字段名通过反射操作实体类的时候需要使用
     * @param rawData
     * @return
     */
    public static String exchangeStringToHump(String rawData){
        List<String> fieldList = Arrays.asList(rawData.split("_"));
        StringBuffer targetString = new StringBuffer();
        // 首个字段全变小写，后续字段首字母大写
        for (int i = 0; i<fieldList.size(); i++){
            if (i == 0){
                targetString.append(fieldList.get(0).toLowerCase());
            }
            else {
                String oneRawField = fieldList.get(i).toLowerCase();
                targetString.append(oneRawField.substring(0,1).toUpperCase()+oneRawField.substring(1));
            }
        }
        return targetString.toString();
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(100);
        list.add(1);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(2);
        list.add(6);
        list.add(9);

        System.out.println(longestConsecutive(list));
    }


    /**
     * 最长连接子序列长度
     * 哈希表+动态规划
     */
    public static int longestConsecutive(List<Integer> list) {
        int result = 0;
        for (int num : list) {
            //若num-1不在哈希表中，说明num是连续序列的第一个元素，由此元素开始遍历
            if (!list.contains(num - 1)) {
                int curNum = num;
                int curLen = 1;
                while (list.contains(curNum + 1)) {
                    curNum++;
                    curLen++;
                }
                result = curLen > result ? curLen : result;
            }
        }

        return result;
    }
}
