[LeetCode] Palindrome Partitioning II
2015-08-24 18:27
281 查看
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.
Well, someone even achieves 4ms running time in C++, which makes me feel like to give a try. I use
class Solution { public: int minCut(string s) { int n = s.length(); vector<int> cut(n + 1); iota(cut.rbegin(), cut.rend(), -1); for (int i = n - 1; i >= 0; i--) { for (int l = i, r = i; l >= 0 && r < n && s[l] == s[r]; l--, r++) cut[l] = min(cut[l], cut[r + 1] + 1); for (int l = i, r = i + 1; l >= 0 && r < n && s[l] == s[r]; l--, r++) cut[l] = min(cut[l], cut[r + 1] + 1); } return cut[0]; } };
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 sto
const char* ssusing
s.c_str(). Now the code takes only 4ms, though looks not so nice :-)
class Solution { public: int minCut(string s) { int n = s.length(), *cut = new int[n + 1]; for (int i = 0; i < n; i++) cut[i] = i - 1; cut = -1; const char *ss = s.c_str(); for (int i = n - 1; i >= 0; i--) { for (int l = i, r = i; l >= 0 && r < n && ss[l] == ss[r]; l--, r++) cut[l] = min(cut[l], cut[r + 1] + 1); for (int l = i, r = i + 1; l >= 0 && r < n && ss[l] == ss[r]; l--, r++) cut[l] = min(cut[l], cut[r + 1] + 1); } return cut[0]; } };
相关文章推荐
- 如何搭建Mantis 缺陷管理系统
- IOS RSA加密解密
- HDU 5411 CRB and puzzle (Dp + 矩阵快速幂)
- 竞品分析脑图
- hibernate简单入门知识
- 多线程GCD
- STL学习----入门(1)[memory]
- oracle学习笔记一:用户管理(3)用户口令管理
- linux下将中文文件名文件cp到windows目录下后文件名乱码问题的解决
- HDU 4135-Co-prime(容斥求区间内与N互质的个数(队列||位运算))
- Palindrome Number
- linux c/c++ 后台开发基础之:c++日志模块
- The Dole Queue(UVA 133)
- ZOJ 3435 Ideal Puzzle Bobble (莫比乌斯反演基础题)
- 范式的数据库具体解释
- php - mysql数据表的内容管理
- UVALive 5987
- java通过rJava调用R失败的问题总结
- 1090. Highest Price in Supply Chain (25) -计层的BFS改进
- CocoaPods安装和使用及问题:Setting up CocoaPods master repo