Leetcode Longest Palindromic Substring problem solution in C# programming

In the Leetcode Longest Palindromic Substring problem solution in C# programming Given a string s, return the longest palindromic substring in s.

Leetcode Longest Palindromic Substring problem solution in C# programming

public class Solution
        {
            public string LongestPalindrome(string s)
            {
                if (string.IsNullOrEmpty(s)) return "";
                int start = 0, length = 0;
                for (int i = 0; i < s.Length ; i++)
                {
                    int len1 = ExpandAroundCenter(s, i, i);
                    int len2 = ExpandAroundCenter(s, i, i + 1);
                    int currLen = Math.Max(len1, len2);
                    if (currLen > length)
                    {
                        start = i - (currLen - 1) / 2;
                        length = currLen;
                    }
                }
                return s.Substring(start, length);
            }
            int ExpandAroundCenter(string s, int left, int right)
            {
                var length = 0;
                while (left >= 0 && right < s.Length && s[left] == s[right])
                {
                    length += left == right ? 1 : 2;
                    --left;
                    ++right;
                    if(left < 0 || right >= s.Length) break;
                }
                return length;
            }
        }

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *