Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace SqliEchallengeLongestPalindromicSubstring
- {
- static class Solution
- {
- public static string LongestPalindromicSubstring(string s)
- {
- int strLength = s.Length;
- int resultLength = 0;
- int resultStart = 0;
- if (strLength < 2)
- {
- return s;
- }
- for (int midPoint = 0; midPoint < strLength - 1; midPoint++)
- {
- /*
- * We start by checking if a substring in a palindrome from its middle.
- * The first call to ExpandRange() takes the first case which is when our substring has a
- * middle point i.e: "sqlilqs". The second one treats the case of when the substring's length
- * is even i.e: "sqliilqs".
- */
- ExpandRange(s, midPoint, midPoint, ref resultLength, ref resultStart);
- ExpandRange(s, midPoint, midPoint + 1, ref resultLength, ref resultStart);
- }
- return s.Substring(resultStart, resultLength);
- }
- static void ExpandRange(String str, int left, int right, ref int resultLength, ref int resultStart)
- {
- /*
- * While the characters starting from the middle on each side are equal, we keep expanding the substring.
- */
- while (left >= 0 && right < str.Length && str[left] == str[right])
- {
- left--;
- right++;
- }
- /*
- * If the resultLength is bigger than the range of the palindrome, we return from the function.
- */
- if (resultLength >= right - left - 1) return;
- resultStart = left + 1;
- resultLength = right - left - 1;
- }
- }
- class Program
- {
- /// <summary>
- /// The application expects a string as input
- /// </summary>
- /// <param name="args"></param>
- public static void Main(string[] args)
- {
- string stringToCheck = Console.ReadLine();
- Console.WriteLine(Solution.LongestPalindromicSubstring(stringToCheck));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement