[LeetCode] Palindrome Partitioning II

简介: This link has two nice solutions, one updating from forth to back (posted by tqlong in the post) and the other updating from back to forth (posted by diego2 in the answer).

This link has two nice solutions, one updating from forth to back (posted by tqlong in the post) and the other updating from back to forth (posted by diego2 in the answer). The reversed updating one, if written in C++ as follows, achieves 12ms, 4ms faster than that of tqlong.

 1 class Solution {
 2 public:
 3     int minCut(string s) {
 4         int n = s.length();
 5         vector<int> cut(n + 1);
 6         iota(cut.rbegin(), cut.rend(), -1);
 7         for (int i = n - 1; i >= 0; i--) {
 8             for (int l = i, r = i; l >= 0 && r < n && s[l] == s[r]; l--, r++)
 9                 cut[l] = min(cut[l], cut[r + 1] + 1);
10             for (int l = i, r = i + 1; l >= 0 && r < n && s[l] == s[r]; l--, r++)
11                 cut[l] = min(cut[l], cut[r + 1] + 1);
12         }
13         return cut[0];
14     }
15 };

Well, someone even achieves 4ms running time in C++, which makes me feel like to give a try. I use int* instead of vector<int> and change string s to const char* ss using s.c_str(). Now the code takes only 4ms, though looks not so nice :-)

 1 class Solution {
 2 public:
 3     int minCut(string s) {
 4         int n = s.length(), *cut = new int[n + 1];
 5         for (int i = 0; i < n; i++) cut[i] = i - 1;
 6         cut[n] = -1;
 7         const char *ss = s.c_str();
 8         for (int i = n - 1; i >= 0; i--) {
 9             for (int l = i, r = i; l >= 0 && r < n && ss[l] == ss[r]; l--, r++)
10                 cut[l] = min(cut[l], cut[r + 1] + 1);
11             for (int l = i, r = i + 1; l >= 0 && r < n && ss[l] == ss[r]; l--, r++)
12                 cut[l] = min(cut[l], cut[r + 1] + 1);
13         }
14         return cut[0];
15     }
16 };

 

目录
相关文章
|
存储
LeetCode 132. Palindrome Partitioning II
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回符合要求的最少分割次数。
102 0
LeetCode 132. Palindrome Partitioning II
LeetCode 131. Palindrome Partitioning
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。
96 0
LeetCode 131. Palindrome Partitioning
[LeetCode] Palindrome Partitioning
The problem has a nice structure that backtracking naturally fits in. The structure is, given a starting position idx, we search from idx till the end of the string s.
665 0
|
3月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
4月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
124 2