Check if a string is a palindrome

后端 未结 30 1568
星月不相逢
星月不相逢 2020-11-28 08:59

I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.

How can I do this?

30条回答
  •  醉酒成梦
    2020-11-28 09:40

    Since a palindrome also includes numbers, words, sentences, and any combinations of these, and should ignore punctuation and case, (See Wikipedia Article) I propose this solution:

    public class Palindrome
    {
        static IList Allowed = new List {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '0'
        };
        private static int[] GetJustAllowed(string text)
        {
            List characters = new List();
            foreach (var c in text)
                 characters.Add(c | 0x20); 
    
            return characters.Where(c => Allowed.Contains(c)).ToArray();
        }
        public static bool IsPalindrome(string text)
        {
            if(text == null || text.Length == 1)
                 return true;
    
            int[] chars = GetJustAllowed(text);
            var length = chars.Length;
    
            while (length > 0)
                if (chars[chars.Length - length] != chars[--length])
                    return false;
    
            return true;
        }
        public static bool IsPalindrome(int number)
        {
            return IsPalindrome(number.ToString());
        }
        public static bool IsPalindrome(double number)
        {
            return IsPalindrome(number.ToString());
        }
        public static bool IsPalindrome(decimal number)
        {
            return IsPalindrome(number.ToString());
        }
    
    }
    

提交回复
热议问题