Change the original string to a new simple string


  • 8
    E

    step1: filter. remove characters not alphanumeric and change all letters to lower case.
    step2; simple string check

     bool checkEasyString(string s){          
        	if(s.size()<=1)return true;
        	int p=0,q=s.size()-1;
        	while(p<q)if(s[p++]!=s[q--])return false;
        	return true;
        }
    
    string filter(string str0){
    	string str;
    	char temp;
    	for(int i=0;i<str0.size();i++){
    		temp=str0[i];
    		if('0'<=temp && temp<='9' )str.push_back(temp);
    		else if('a'<=temp && temp<='z')str.push_back(temp);
    		else if('A'<=temp && temp<='Z')str.push_back(temp-('A'-'a'));
    	}
    	return str;
    }
    
    
    bool isPalindrome(string s) {
        return checkEasyString(filter(s));
    }

  • 3
    L

    would be simpler using regular expression

    public class Solution {
        public boolean isPalindrome(String s) {
            
             //replace non letter char to ""
    	        s=s.replaceAll("\\W","");
    	        s=s.toLowerCase();
    	        int n = s.length();
    	        int i=0,j=n-1;
    	        while(i<j){
    	            if(s.charAt(i)!=s.charAt(j)) return false;
    	            
    	            i++;j--;
    	        }
    	        return true;
    	    
        }
    }

  • 1
    V

    Using a helper function isValidCharacter(char ch) might be useful if in case there is a constraint that new string shouldn't be created.

    class Solution{
        public:
    bool isPalindrome(string s) {
        int startPos = 0, endPos = s.size() - 1;
        while (startPos < endPos) {
            if (!isValidCharacter(s[startPos])) { startPos ++; continue; }
            if (!isValidCharacter(s[endPos])) { endPos --; continue; }
            if (s[startPos] != s[endPos] && abs(s[startPos] - s[endPos]) != 32) return false;
            startPos ++;
            endPos --;
        }
        return true;
    }
    bool isValidCharacter(char ch) {
        return ((ch >= '0' && ch <= '9') ||(ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
    }
    };

  • 0
    S

    isPalindrome("1Q") will return true.

    You should not use abs(s[startPos] - s[endPos]) != 32 .


Log in to reply
 

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