C# solution with explanation


  • 0
    K
    public class Solution {
        public int LongestPalindrome(string s) {
            
            int count = 0;
            //move the string characters to a list and sort the list
            List<char> list = new List<char>();
            for (int i=0;i<s.Length;i++)
            {
                list.Add(s[i]);
            }
            list.Sort();
            //find the double characters, count them and remove them from the list
            for (int i=list.Count-1;i>0;i--)
            {
                if (list[i] == list[i-1])
                {
                    list.RemoveAt(i);
                    list.RemoveAt(i-1);
                    i--;
                    count++;
                }
            }
            count = count * 2;
            //if any character left in the list then we can use it as the middle character of the palindrome, so we add it to the count
            if (list.Count>0) count++;
            return count;
        }
    }
    

Log in to reply
 

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