Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to validate palindromes in C++

Shulou Source: shulou.com Published: 2022-05-31 13:54:14 10月03日 Update

This article mainly explains "how C++ validates palindromes". The explanation in the article is simple and clear and easy to learn and understand. Please follow the editor's ideas slowly and deeply. Let's study and learn how C++ validates palindromes.

Valid Palindrome validate palindrome string

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

Note:

Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

Validating palindromes is a common problem. Palindromes are strings that are the same for both positive and negative reading. For example, "level" or "noon" are palindromes. But here, added spaces and non-alphanumeric characters, increased some difficulty, but the principle is still very simple: just set up two pointers, left and right, respectively, from the beginning and the end of the character to traverse the entire string, if you encounter non-alphanumeric characters to skip, continue to look down, until the next alphanumeric or the end of the traversal, if you encounter uppercase letters, it will be converted to lowercase. When both the left and right pointers find alphanumeric characters, compare the two characters. If they are equal, continue to compare the alphanumeric characters found below. If not, return false directly.

The time complexity is O (n) and the code is as follows:

Solution 1:

Class Solution {public: bool isPalindrome (string s) {int left = 0, right = s.size ()-1; while (left

< right) { if (!isAlphaNum(s[left])) ++left; else if (!isAlphaNum(s[right])) --right; else if ((s[left] + 32 - "a") %32 != (s[right] + 32 - "a") % 32) return false; else { ++left; --right; } } return true; } bool isAlphaNum(char &ch) { if (ch >

= "a" & & ch = "A" & & ch = "0" & & ch

Tags: Characters palindromes strings validations letters numbers Clippers two namely learning code content pointers solutions problems complexity functions principles complexity capitalization Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MariaDB MySQL Redmi NVidia