C# solution with two pointer and custom function to check char is alphanumeric or not


  • 1
    M

    Below is C# solution. I created my own function to check if char is alphanumeric or not.

    public class Solution {
        private bool isAlphaNuemric (char ch)
        {
            if ((ch -'a' >=0 && ch - 'z' <= 0) || (ch -'A' >= 0  && ch -'Z' <=0  ) || (ch -'0' >= 0 && ch -'9' <= 0))
            {
                return true;
            } else
            {
                return false;
            }
        }
        
        public bool IsPalindrome(string s) {
            if (s == String.Empty || s.Length < 1)
                return true;
            
            int startIndex = 0;
            int endIndex = s.Length - 1;
            while (startIndex < endIndex )
            {
               // ignore all other charcter except alphnumeric 
                if (!isAlphaNuemric(s[startIndex]))
                {
                    startIndex++;
                    continue;
                }
                
                if (!isAlphaNuemric(s[endIndex]))
                {
                    endIndex--;
                    continue;
                }
                
                if (Char.ToLower(s[startIndex]) == Char.ToLower(s[endIndex]) )
                {
                    startIndex++;
                    endIndex--;
                } else
                {
                    return false;
                }
            } 
           return true;       
       }
    }
    

  • 0
    M

    Very nice solution! I think isAlphaNumeric() might be better satisfied as one line:

    return ((ch -'a' >=0 && ch - 'z' <= 0) || (ch -'A' >= 0  && ch -'Z' <=0  ) || (ch -'0' >= 0 && ch -'9' <= 0));
    

Log in to reply
 

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