LeetCode 471: Encode String with Shortest Length

Note:

1. We start with different position and different length to find the shortening.

2. It satisfy following conditions :

             I. if length < 4, it short does not help. number [char] takes four pos.

             II. Since shortening happen, we can see whether a substring can be combined by two shortened words. k from [i, j]. dp[i][k] and dp[k + 1][j].

             III Find all the possible shortening: i) length module should be 0. ii)) After all the replacement length should be 0.

class Solution {
    public String encode(String s) {
        String[][] dp = new String[s.length()][s.length()];
        
        for (int l = 0; l < s.length(); l++) {
            for (int i = 0; i < s.length() - l; i++) {
                int j = i + l;
                String subStr = s.substring(i, j + 1);
                dp[i][j] = subStr;
                if (j - i < 4) {
                    continue;
                }
                for (int k = i; k < j; k++) {
                    if ((dp[i][k].length() + dp[k + 1][j].length()) < dp[i][j].length()) {
                        dp[i][j] = dp[i][k] + dp[k + 1][j];
                    }
                }
                
                for (int k = 0; k < subStr.length(); k++) {
                    String repeat = subStr.substring(0, k + 1);
                    if (repeat != null && subStr.length() % repeat.length() == 0 && subStr.replaceAll(repeat, "").length() == 0) {
                        String result = subStr.length() / repeat.length() + "[" + dp[i][i + k] + "]";
                        if (result.length() < dp[i][j].length()) {
                            dp[i][j] = result;
                        }
                    }
                }
            }
        }
        return dp[0][s.length() - 1];
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7672517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值