| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.LongestPalindromicSubstring; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestPalindromicSubstringTwoPointers : ILongestPalindromicSubstring |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public string LongestPalindrome(string s) |
| 12 | 24 | | { |
| 12 | 25 | | if (string.IsNullOrEmpty(s)) |
| 1 | 26 | | { |
| 1 | 27 | | return string.Empty; |
| | 28 | | } |
| | 29 | |
|
| 11 | 30 | | var left = 0; |
| 11 | 31 | | var right = 0; |
| | 32 | |
|
| 224 | 33 | | for (var i = 0; i < s.Length; i++) |
| 101 | 34 | | { |
| 101 | 35 | | var oddLength = ExpandAroundCenter(s, i, i); |
| 101 | 36 | | var evenLength = ExpandAroundCenter(s, i, i + 1); |
| | 37 | |
|
| 101 | 38 | | var maxLength = Math.Max(oddLength, evenLength); |
| | 39 | |
|
| 101 | 40 | | if (maxLength <= right - left) |
| 67 | 41 | | { |
| 67 | 42 | | continue; |
| | 43 | | } |
| | 44 | |
|
| 34 | 45 | | left = i - ((maxLength - 1) / 2); |
| 34 | 46 | | right = i + (maxLength / 2); |
| 34 | 47 | | } |
| | 48 | |
|
| 11 | 49 | | return s.Substring(left, right - left + 1); |
| 12 | 50 | | } |
| | 51 | |
|
| | 52 | | private static int ExpandAroundCenter(string s, int left, int right) |
| 202 | 53 | | { |
| 352 | 54 | | while (left >= 0 && right < s.Length && s[left] == s[right]) |
| 150 | 55 | | { |
| 150 | 56 | | left--; |
| 150 | 57 | | right++; |
| 150 | 58 | | } |
| | 59 | |
|
| 202 | 60 | | return right - left - 1; |
| 202 | 61 | | } |
| | 62 | | } |