8000 5. Longest Palindromic Substring · nullskill/leetcode@408b968 · GitHub
[go: up one dir, main page]

Skip to content

Commit 408b968

Browse files
committed
5. Longest Palindromic Substring
1 parent 06ee464 commit 408b968

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import 'dart:math';
2+
3+
/// The time complexity of the `longestPalindrome` function is `O(n^2)`,
4+
/// where `n` is the length of the input string `s`. This is because we
5+
/// loop over each character in `s` and call the `expandAroundCenter`
6+
/// function twice for each character. The `expandAroundCenter` function
7+
/// has a time complexity of `O(n)`, where `n` is the length of the input
8+
/// string `s`, because in the worst case we need to expand around the
9+
/// center of the string for each character in the string.
10+
/// The space complexity of the longestPalindrome function is `O(1)`
11+
12+
class Solution {
13+
String longestPalindrome(String s) {
14+
if (s.isEmpty) return '';
15+
16+
int start = 0;
17+
int end = 0;
18+
19+
for (int i = 0; i < s.length; i++) {
20+
int len1 = expandAroundCenter(s, i, i);
21+
int len2 = expandAroundCenter(s, i, i + 1);
22+
int len = max(len1, len2);
23+
if (len > end - start) {
24+
start = i - (len - 1) ~/ 2;
25+
end = i + len ~/ 2;
26+
}
27+
}
28+
29+
return s.substring(start, end + 1);
30+
}
31+
32+
int expandAroundCenter(String s, int left, int right) {
33+
while (left >= 0 && right < s.length && s[left] == s[right]) {
34+
left--;
35+
right++;
36+
}
37+
return right - left - 1;
38+
}
39+
}
40+
41+
void main(List<String> args) {
42+
print(Solution().longestPalindrome('abcabcbb'));
43+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
5. Longest Palindromic Substring
2+
https://leetcode.com/problems/longest-palindromic-substring/
3+
4+
Given a string s, return the longest
5+
palindromic substring in s.
6+
7+
8+
Example 1:
9+
10+
Input: s = "babad"
11+
Output: "bab"
12+
Explanation: "aba" is also a valid answer.
13+
14+
Example 2:
15+
16+
Input: s = "cbbd"
17+
Output: "bb"
18+
19+
20+
Constraints:
21+
22+
1 <= s.length <= 1000
23+
s consist of only digits and English letters.

0 commit comments

Comments
 (0)
0