19 Sep 2023, 3:17 PM
19 Sep 2023, 3:17 PM

9. Valid Palindrome

#leetcode/125

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Solution

Solution in C++ using two pointers

The solution is very simple.

Finally, after checking all characters, the string must be a valid palindrome so we can return true.

bool isPalindrome(string s) {
	for(int start = 0, end = s.size() - 1; start < end;) {
		/* If s[start] is a num we can drop it */
		if(!isalnum(s[start]))
			start++;
		/* If s[end] is a num we can drop it */
		else if(!isalnum(s[end]))
			end--;
		/* If the two compared characters aren't equal, return false */
		/* We don't need to care about doing tolower() on a number, it will return the same result for both number */
		else if(tolower(s[start]) != tolower(s[end]))
			return false;
		/* If the two compared characters are equal */
		else {
			start++;
			end--;
		}
	}
	return true;
}