分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

LeetCode 471: Encode String with Shortest Length

发布时间:2023-09-06 01:17责任编辑:彭小芳关键词:暂无标签

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]; ???}}

LeetCode 471: Encode String with Shortest Length

原文地址:http://www.cnblogs.com/shuashuashua/p/7672517.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved