您的位置:首页 > 其它

[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.

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 s
to
const char* ss
using
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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: