Valid Palindrome

Valid Palindrome 

Judgment palindrome character skewer

This can be achieved by maintaining two pointers, that is, one starts to traverse from the left, and the other starts to traverse from the right, and spaces need to be processed when traversing.

The source code is as follows:

C++ version:

class Solution {
public:
    bool isPalindrome (string s) {        
	    int start=0, end=s.length()-1;
	    while(start<end) {
		    if (!isalnum(s[start]))
                start++;
		    else if (!isalnum(s[end]))
                end--;
		    else {
		    	if (tolower(s[start++])!=tolower(s[end--]))
                    return false;
	    	}
    	}
	    return true;
    }
};
JAVA version:

public class Solution {	
	public boolean isPalindrome(String s) {
		if (s == null) {
			return true;
		}
		
		int i = 0;
		int j = s.length() - 1;
		while (i < j) {
			if (!isAlphanumeric(s.charAt(i))) {
				i++;
				continue;
			}
			if (!isAlphanumeric(s.charAt(j))) {
				j--;
				continue;
			}
			if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))) {
				i++;
				j--;
				continue;
			}
			return false;
		}
		return true;
	}	
	public boolean isAlphanumeric(char c) {
		if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
			return true;
		}
		return false;
	}    
	
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326350823&siteId=291194637