10000 added 119 · xiaokai1996/LeetCode-1@4fbfb7e · GitHub
[go: up one dir, main page]

Skip to content

Commit 4fbfb7e

Browse files
committed
added 119
1 parent a8aad41 commit 4fbfb7e

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Question is Longest Palindromic Substring.
2+
3+
假设 S(i, j) 为问题的解,即从位置 `i``j` 的字符串是 Longest Palindromic Substring of the string.
4+
5+
我们从最简单的字符串来想:
6+
7+
a
8+
9+
单字符本身是否是回文?是。即 S(i, i)
10+
11+
a a
12+
13+
两个相同字符是否组成回文?是。即 S(i, i+1) when `s[i] == s[i+1]`.
14+
15+
b a a b
16+
17+
为上面的回文字符串首尾增加一个相同的字符 `b`, 组成了回文,即 S(i, j) when S(i+1, j-1) and `s[i] == s[j]`.
18+
19+
**由于我们持续在首尾增加字符,对于单字符,则长度一直为奇数;对于双字符,则长度一直为偶数。所以要涵盖所有情况,需要分别验证这两种情况。**
20+
21+
好了,分析到这里基本可以明白回文的规律所在了。
22+
23+
要求的是长度,那么我们记 Longest Palindromic Substring 为 longest.
24+
25+
```cpp
26+
void longestPalindrome(const string& s, int b, int e, int &start, int &last) {
27+
// 这个函数尝试对现有子串首尾扩张,若出现更大的长度,则记录之。
28+
int len = s.size();
29+
while (b >= 0 && e < len && s[b] == s[e])
30+
--b, ++e;
31+
++b, --e;
32+
if (e - b > last - start) {
33+
start = b;
34+
last = e;
35+
}
36+
}
37+
```
38+
39+
主函数里就非常轻松惬意了。
40+
41+
```cpp
42+
string longestPalindrome(string s) {
43+
int len = s.size();
44+
if (len == 0) return s;
45+
int start = 0, last = 0;
46+
for (int i=0; i<len-1; ++i) {
47+
longestPalindrome(s, i, i, start, last); // 奇数情况
48+
longestPalindrome(s, i, i+1, start, last); // 偶数情况
49+
}
50+
return s.substr(start, last-start+1);
51+
}
52+
```
53+
54+
时间复杂度应该在 O(n^2), 空间复杂度为 O(1). 属于常规解法。
55+
56+
-----
57+
58+
此题可以做到 O(n) 的时间复杂度。请参考[这里](http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#define CATCH_CONFIG_MAIN
2+
#include "../Catch/single_include/catch.hpp"
3+
#include "solution.h"
4+
5+
TEST_CASE("Longest Palindromic Substring", "longestPalindrome")
6+
{
7+
Solution s;
8+
REQUIRE( s.longestPalindrome("abbabbua") == "bbabb");
9+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <string>
2+
using std::string;
3+
4+
class Solution {
5+
void longestPalindrome(const string& s, int b, int e, int &start, int &last) {
6+
int len = s.size();
7+
while (b >= 0 && e < len && s[b] == s[e])
8+
--b, ++e;
9+
++b, --e;
10+
if (e - b > last - start) {
11+
start = b;
12+
last = e;
13+
}
14+
}
15+
16+
public:
17+
string longestPalindrome(string s) {
18+
int len = s.size();
19+
if (len == 0) return s;
20+
int start = 0, last = 0;
21+
for (int i=0; i<len-1; ++i) {
22+
longestPalindrome(s, i, i, start, last);
23+
longestPalindrome(s, i, i+1, start, last);
24+
}
25+
return s.substr(start, last-start+1);
26+
}
27+
};

0 commit comments

Comments
 (0)
0