Skip to content

Commit d549a85

Browse files
Add files via upload
1 parent 3ff4efe commit d549a85

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Runtime: 48 ms, faster than 52.20% of C++ online submissions for Longest Palindromic Substring.
2+
// Memory Usage: 16 MB, less than 39.08% of C++ online submissions for Longest Palindromic Substring.
3+
4+
class Solution {
5+
public:
6+
string longestPalindrome(string s) {
7+
// 边界条件处理
8+
string res = "";
9+
if (s.length() == 0) return res;
10+
11+
int maxLength = 0;
12+
for (int center = 0; center < s.length(); ++center) {
13+
int curLength[] = { 1, 0 }, leftPtr[] = { center, center + 1 }, rightPtr[] = { center, center };
14+
for (int i = 0; i < 2; ++i) {
15+
while (--leftPtr[i] >= 0 && ++rightPtr[i] < s.length() && s[leftPtr[i]] == s[rightPtr[i]])
16+
curLength[i] += 2;
17+
18+
if (curLength[i] > maxLength) {
19+
res = s.substr(++leftPtr[i], curLength[i]);
20+
maxLength = curLength[i];
21+
}
22+
}
23+
}
24+
return res;
25+
}
26+
};

0 commit comments

Comments
 (0)