LC 215. Valid Palindrome

Sarthak Sehgal · April 11, 2020

The question is pretty straightforward. You just have to take care of edge cases where a character in the string may not be an alphabet or a number. Below is a short code which employs two pointer approach and takes the edge cases into care by checking that both pointers always point to a valid character:

bool isPalindrome(string s) {
		int l = 0, r = s.length()-1;

		while (l<r) {
				if (!isalnum(s[l]))
						l++;
				else if (!isalnum(s[r]))
						r--;
				else if (tolower(s[l]) != tolower(s[r]))
						return false;
				else
						l++, r--;
		}

		return true;
}

Time complexity: O(n)

Twitter, Facebook