| | 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 | | using System.Text; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.ShortestPalindrome; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class ShortestPalindromeTwoPointers : IShortestPalindrome |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n^2) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public string ShortestPalindrome(string s) |
| 12 | 26 | | { |
| 12 | 27 | | if (s.Length <= 1) |
| 4 | 28 | | { |
| 4 | 29 | | return s; |
| | 30 | | } |
| | 31 | |
|
| 8 | 32 | | var left = 0; |
| | 33 | |
|
| 136 | 34 | | for (var right = s.Length - 1; right >= 0; right--) |
| 60 | 35 | | { |
| 60 | 36 | | if (s[right] == s[left]) |
| 51 | 37 | | { |
| 51 | 38 | | left++; |
| 51 | 39 | | } |
| 60 | 40 | | } |
| | 41 | |
|
| 8 | 42 | | if (left == s.Length) |
| 4 | 43 | | { |
| 4 | 44 | | return s; |
| | 45 | | } |
| | 46 | |
|
| 4 | 47 | | var resultStringBuilder = new StringBuilder(); |
| | 48 | |
|
| 4 | 49 | | var nonPalindromeSuffix = s[left..]; |
| | 50 | |
|
| 26 | 51 | | for (var i = nonPalindromeSuffix.Length - 1; i >= 0; i--) |
| 9 | 52 | | { |
| 9 | 53 | | resultStringBuilder.Append(nonPalindromeSuffix[i]); |
| 9 | 54 | | } |
| | 55 | |
|
| 4 | 56 | | resultStringBuilder.Append(ShortestPalindrome(s[..left])); |
| 4 | 57 | | resultStringBuilder.Append(nonPalindromeSuffix); |
| | 58 | |
|
| 4 | 59 | | return resultStringBuilder.ToString(); |
| 12 | 60 | | } |
| | 61 | | } |