My C++ Solution


  • 0
    class Solution {
    public:
        bool isPalindrome(string s) {
            if (s.empty()) return true;
    		string::iterator low  = s.begin();
    		string::iterator high = s.end() - 1;
    		while((high - low) >= 1){
    			while (!isalnum(*low)){
    				++low;
    				if (low >= s.end()) return true;
    			}
    			while (!isalnum(*high))
    				--high;
    			if (tolower(*low) != tolower(*high))
    				return false;
    			++low;
    			--high;
    		}
    		return true;
        }
    };

  • 0
    S
    class Solution {
    public:
        bool isPalindrome(string s) {
            if (s.size() == 0) return true;
            int i = 0, j = s.size() - 1;
            while(i < j){
              if(!isalnum(s[i])){++i; continue;}
              if(!isalnum(s[j])){--j; continue;}
              if (tolower(s[i]) != tolower(s[j])) return false;
              i++;
              j--;
            }
            return true;
        }
    };
    

    Subscripts can also be used instead of using iterator.


  • 0
    K

    class Solution {
    public:
    bool isPalindrome(string &s) {
    if (s.empty())
    {
    return true;
    }

    	int len = s.length();		
    	int i = 0,j = len;	
    	while(i!=j){
    		while(!isalnum(s[i]) && i<len) ++i;
    		while(!isalnum(s[j]) && j>=0) --j;
    
    		if (i>=len ||j<0)
    		{
    			break;
    		}
    		if (tolower(s[i])!=tolower(s[j]))
    		{
    			return false;
    		}
    		++i,--j;
    	}
    	return true;
    
    }
    

    };


Log in to reply
 

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