|
| 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 | +} |
0 commit comments