Advertisement
butbanksy

Untitled

Nov 29th, 2020 (edited)
652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SqliEchallengeLongestPalindromicSubstring
  4. {
  5.     static class Solution
  6.     {
  7.         public static string LongestPalindromicSubstring(string s)
  8.         {
  9.             int strLength = s.Length;
  10.             int resultLength = 0;
  11.             int resultStart = 0;
  12.             if (strLength < 2)
  13.             {
  14.                 return s;
  15.             }
  16.  
  17.             for (int midPoint = 0; midPoint < strLength - 1; midPoint++)
  18.             {
  19.                 /*
  20.                  * We start by checking if a substring in a palindrome from its middle.
  21.                  * The first call to ExpandRange() takes the first case which is when our substring has a
  22.                  * middle point i.e: "sqlilqs". The second one treats the case of when the substring's length
  23.                  * is even i.e: "sqliilqs".
  24.                  */
  25.                 ExpandRange(s, midPoint, midPoint, ref resultLength, ref resultStart);
  26.                 ExpandRange(s, midPoint, midPoint + 1, ref resultLength, ref resultStart);
  27.             }
  28.  
  29.             return s.Substring(resultStart, resultLength);
  30.         }
  31.  
  32.         static void ExpandRange(String str, int left, int right, ref int resultLength, ref int resultStart)
  33.         {
  34.             /*
  35.              * While the characters starting from the middle on each side are equal, we keep expanding the substring.
  36.              */
  37.             while (left >= 0 && right < str.Length && str[left] == str[right])
  38.             {
  39.                 left--;
  40.                 right++;
  41.             }
  42.             /*
  43.              * If the resultLength is bigger than the range of the palindrome, we return from the function.
  44.              */
  45.             if (resultLength >= right - left - 1) return;
  46.             resultStart = left + 1;
  47.             resultLength = right - left - 1;
  48.         }
  49.     }
  50.  
  51.     class Program
  52.     {
  53.         /// <summary>
  54.         /// The application expects a string as input
  55.         /// </summary>
  56.         /// <param name="args"></param>
  57.         public static void Main(string[] args)
  58.         {
  59.             string stringToCheck = Console.ReadLine();
  60.             Console.WriteLine(Solution.LongestPalindromicSubstring(stringToCheck));
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement