public static int parse(String sentence, HashSet<String> dictionary) {
        if (sentence == null || sentence.isEmpty()) return 0;
        int len = sentence.length();
        if (dictionary == null || dictionary.isEmpty()) return len;
        int[] dp = new int[len + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 1; i <= len; ++i) {
            for (int j = 0; j < i; ++j) {
                String word = sentence.substring(j, i);
                int unrecogCharNum = dictionary.contains(word) ? 0 : word.length();
                int totalUnrecogCharNum = dp[j] + unrecogCharNum;
                if (totalUnrecogCharNum < dp[i]) dp[i] = totalUnrecogCharNum;
                // recurrence:
                // dp[i] = min(dp[i], dp[j] + unrecogCharNum)
                // where dp[n] is minimal number of unrecognized chars in first n chars
            }
        }
        return dp[len];
    }