C# 216ms 43lines clear format


  • 0
    public class Solution {
        private int sIndex=0;
        private int palindromeLength=0;
        public string LongestPalindrome(string s) {
            string returnString="";
            if(!String.IsNullOrEmpty(s))
            {
                if(s.Length<2)
                {
                    returnString=s;
                }
                else
                {
                    for(int i=0;i<s.Length-1;i++)
                    {
                        //odd
                        scanPalindrome(s,i,i);
                        //even
                        scanPalindrome(s,i,i+1);
                    }
                    returnString=s.Substring(sIndex,palindromeLength);
                }
            }
            else
            {
                returnString=s;
            }
            return returnString;
        }
        public void scanPalindrome(string s,int frontIndex,int backIndex)
        {
            while(frontIndex>=0&&backIndex<s.Length&&s[frontIndex]==s[backIndex])
            {
                frontIndex--;
                backIndex++;
            }
            if(palindromeLength<backIndex-frontIndex-1)
            {
                sIndex=frontIndex+1;
                palindromeLength=backIndex-frontIndex-1;
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.