LeetCode - Palindrome Partitioning II 题解
来源:互联网 发布:怎么把照片导入mac 编辑:程序博客网 时间:2024/05/19 17:58
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
这题卡时间卡的很严,自认为N^2的算法还是超时
1.
class Solution {public: int minCut(string s) { int l = s.length(); if(l <= 1) return 0; P = vector<vector<bool> > (l, vector<bool> (l, false)); for(int i = 0; i < l; ++i){ P[i][i] = true; if(i + 1 < l){ P[i][i + 1] = (s[i] == s[i + 1]); } } for(int k = 2; k < l; ++k) for(int i = 0; i + k < l; ++i) { P[i][i + k] = (s[i] == s[i + k]) && P[i + 1][i + k -1]; } vector<int> F(l, l - 1); F[0] = 0; for(int i = 1; i < l; ++i){ if(P[0][i]){ F[i] = 0; continue; } for(int j = 1; j <= i; ++j){ if(P[j][i]){ F[i] = min(F[i], F[j - 1] + 1); } } } return F[l - 1]; }private: vector<vector<bool> > P;};
2.可以离散化成每一个回文词判断一次,就过了
class Solution {public: int minCut(string s) { int l = s.length(); if(l <= 1) return 0; P = vector<vector<bool> > (l, vector<bool> (l, false)); vector<int> F(l, 0); for(int i = 0; i < l; ++i){ F[i] = i; } for(int i = 0; i < l; ++i){ for(int j = i; j >= 0; --j){ if(s[i] == s[j] && (i - j < 2 || P[j + 1][i - 1])){ P[j][i] = true; F[i] = min(F[i], j == 0 ? 0 : F[j - 1] + 1); } } } return F[l - 1]; }private: vector<vector<bool> > P;};
0 0
- Palindrome Partitioning II|leetcode题解
- LeetCode - Palindrome Partitioning II 题解
- LeetCode 题解(90): Palindrome Partitioning II
- LeetCode题解:Palindrome Partitioning
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- LeetCode - Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- 2015-1-26工作日志-王亮晶
- 批量下载宝宝吧故事集工具
- Core Java笔记—第4章 对象与类
- 【linux学习日记】Windows_grub引导的修复
- Kafka的Producer和Consumer源码学习
- LeetCode - Palindrome Partitioning II 题解
- patch文件的格式(ns2的)
- MoreWindows博客目录(微软最有价值专家博客,原创技术文章152篇,访问量164万)
- Linux 串口编程
- spring+hibernate 关联映射
- 工作日志
- 101个MySQL的调节和优化的提示
- 数组中只出现一次的数
- python学习:继承