Given a non-empty string, encode the string such that its encoded length is the shortest.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.

Note:
k will be a positive integer and encoded string will not be empty or have extra space.
You may assume that the input string contains only lowercase English letters. The string's length is at most 160.
If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return any of them is fine.
Example 1: Input: "aaa"
Output: "aaa"
Explanation: There is no way to encode it such that it is shorter than the input string, so we do not encode it.
Example 2: Input: "aaaaa"
Output: "5[a]"
Explanation: "5[a]" is shorter than "aaaaa" by 1 character.
Example 3: Input: "aaaaaaaaaa"
Output: "10[a]"
Explanation: "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
Example 4: Input: "aabcaabcd"
Output: "2[aabc]d"
Explanation: "aabc" occurs twice, so one answer can be "2[aabc]d".
Example 5: Input: "abbbabbbcabbbabbbc"
Output: "2[2[abbb]c]"
Explanation: "abbbabbbc" occurs twice, but "abbbabbbc" can also be encoded to "2[abbb]c", so one answer can be "2[2[abbb]c]".

DP:

Initially I think of 1D DP, dp[i] stands for the shortest string of first i characters, then:

dp[i] = minLen{dp[k] + encode(substring(k+1, i))}

then I realize that the second part encode(substring(k+1, i)) is actually the same with our dp problem. So it turns out the transfer function is

dp[i] = minLen{dp[k] + dp(substring(k+1, i))}

then 1D is not enough, I introduce the second dimension, which indicates the end. dp[i][j] is the shortest encoded string from i to j

But the hardest part of this problem is how to generate dp[i][j] from dp[i][k] and dp[k+1][j]

I've thought about the cases like:

dp[i][k] = 3[abc]   dp[k+1][j] = 2[abc],   then dp[i][j] = 5[abc]

dp[i][k] = 3[abc]   dp[k+1][j] = xyz,   then dp[i][j] = 3[abc]xyz

dp[i][k] = aabc   dp[k+1][j] = aabc,   then dp[i][j] = 2[aabc]

No idea what to implement this conveniently, so refer to idea  https://discuss.leetcode.com/topic/71963/accepted-solution-in-java

The idea is to firstly concantenate dp[i][k] and dp[k+1][j] directly to construct dp[i][j], and then check if there exist possible repeat patterns in the original substring s.substring(i, j+1) that could further shorten dp[i][j]

replaceAll function is really clever

Time Complexity is O(N^4), replaceAll() is O(N)

 public class Solution {
public String encode(String s) {
if (s==null || s.length()==0) return "";
String[][] dp = new String[s.length()][s.length()]; for (int len=0; len<s.length(); len++) {
for (int i=0; i+len<s.length(); i++) {
int j = i + len;
String subStr = s.substring(i, j+1);
dp[i][j] = subStr; //initialize
if (len < 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];
}
} //check if subStr has repeat pattern
for (int k=i; k<j; k++) {
String repeat = s.substring(i, k+1);
if (subStr.length()%(k-i+1)==0 && subStr.replaceAll(repeat, "").length()==0) {
String ss = subStr.length()/repeat.length() + "[" + dp[i][k] + "]";
if (ss.length() < dp[i][j].length())
dp[i][j] = ss;
}
}
}
}
return dp[0][s.length()-1];
}
}

Leetcode: Encode String with Shortest Length && G面经的更多相关文章

  1. [LeetCode] Encode String with Shortest Length 最短长度编码字符串

    Given a non-empty string, encode the string such that its encoded length is the shortest. The encodi ...

  2. [LeetCode] Decode String 解码字符串

    Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where ...

  3. LeetCode : Given a string, find the length of the longest serial substring without repeating characters.

    Given a string, find the length of the longest serial substring without repeating characters. Exampl ...

  4. Leetcode: Encode and Decode TinyURL

    Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...

  5. Leetcode 943. Find the Shortest Superstring(DP)

    题目来源:https://leetcode.com/problems/find-the-shortest-superstring/description/ 标记难度:Hard 提交次数:3/4 代码效 ...

  6. [LeetCode] Encode and Decode TinyURL 编码和解码精简URL地址

    Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...

  7. Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...

  8. 05_整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

    Question: 整理String类的Length().charAt(). getChars().replace(). toUpperCase(). toLowerCase().trim().toC ...

  9. 数组有没有length()这个方法? String有没有length()这个方法?

    答:数组和string都没有Length()方法,只有Length属性.

随机推荐

  1. 【前端开发】优化代码之减少引入,css预编译语言的优点,stylus的使用

    前言:我必须得承认在最最最开始的时候,我对于css的预编译是非常不以为然的,这是错误的.一般在页面编写过程中,我会将需要reset的css放在reset.css中,讲会需要重复用到的放置到public ...

  2. Codeforces Round #354 (Div. 2)

    贪心 A Nicholas and Permutation #include <bits/stdc++.h> typedef long long ll; const int N = 1e5 ...

  3. 设置R启动时自动加载常用的包或函数

    在我前面的文章(http://www.cnblogs.com/homewch/p/5749850.html)中有提到R可以自定义启动环境,需要修改R安装文件中的ect文件夹下的配置文件Rprofile ...

  4. css3动画----实现动态省略号 ...

    <h3>实现省略号点点动,纯css3实现动态省略号</h3>上传中<span class="dot">...</span> [css ...

  5. Python实战:扫描key完整性

    之前在国际版本中,需要支持中英文切换功能,在如此繁多的源文件里要查找源文件里的key是语言资源包是否对应. 正好运用在之前学的python,写了个工具,支持自定义替换标签,批量处理源文件.现在看来,效 ...

  6. Web.xml各版本模版

    web.xml v2.3 web.xml v2.4 <?xml version="1.0" encoding="UTF-8"?> <web-a ...

  7. js 的match方法

    怎么调用? 字符串对象.match( 目标串 ); 返回值? 如果存在,就返回这个字符串: 否则, 返回null 实例 举一个常用的例子,判断图片路径是否包含某个字符串.

  8. stl循环删除

    struct st_data { st_data(int i) : id(i) {} int id; }; 对于STL标准序列容器vector/deque/list(以vector为例) 当我们需清空 ...

  9. Unity -- EventSystem完全掌握

    Event System 组成 系统生成的Event System里面主要有两个Components,分别是Event System和Standalone Input Module. 其中Standa ...

  10. 【转】自学成才秘籍!机器学习&深度学习经典资料汇总

      小编都深深的震惊了,到底是谁那么好整理了那么多干货性的书籍.小编对此人表示崇高的敬意,小编不是文章的生产者,只是文章的搬运工. <Brief History of Machine Learn ...