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. 浅谈SQLiteOpenHelper之onCreate例子

    哈喽大家好!如果你感觉SQLiteOpenHelper不懂的可以看一下.  onCreate(SQLiteDatabase db) : 当数据库被首次创建时执行该方法,一般将创建表等初始化操作在该方法 ...

  2. Bestcoder Round #84

    A题 Aaronson http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=718&pid=1001 感觉一 ...

  3. iOS--NSTimer设置定时器的两种方法

    //方法一: //创建定时器 NSTimer *timer=[NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(next ...

  4. 【BZOJ1076】[SCOI2008]奖励关 状压DP+期望

    [BZOJ1076][SCOI2008]奖励关 Description 你正在玩你最喜欢的电子游戏,并且刚刚进入一个奖励关.在这个奖励关里,系统将依次随机抛出k次宝物,每次你都可以选择吃或者不吃(必须 ...

  5. PHP mysql基础操作

    mysql连接操作 //建立连接$con = mysql_connect('localhost', 'root', '123456');//判断是否连接成功if($con){ die('连接失败!'. ...

  6. java.lang.NoSuchMethodError:

    Servlet.service() for servlet [springMVC] in context with path [/mobile] threw exception [Handler pr ...

  7. 如何激活win10 win10激活工具下载

    http://www.2cto.com/os/201511/448815.html 官方的win10出来了,可是装在上电脑后要花钱才能用,费用要好几百呢,感觉很不值得,这里我教给大家个免费激活官方wi ...

  8. harris角点检测的学习

    Harris通过运用微分运算和自相关矩阵改进了Moravec角点检测算法.用微分算子重新定义灰度强度变化的公式,其灰度强度变化表示为: 式中的wu,v为高斯窗口在(u,v)处的系数.X,Y它们是像素点 ...

  9. 【手把手教你Maven】构建过程

    Maven是一款进行 依赖管理.项目构建.信息管理 为一体的工具. 它不像Make具有复杂的命令.也不像Ant需要手动编写大量的重复代码就能进行项目的构建: 还能提供强大的依赖库管理,避免jar包混乱 ...

  10. 如何提高Java并行程序性能??

    在Java程序中,多线程几乎已经无处不在.与单线程相比,多线程程序的设计和实现略微困难,但通过多线程,我们却可以获得多核CPU带来的性能飞跃,从这个角度说,多线程是一种值得尝试的技术.那么如何写出高效 ...