Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to validate palindromes in C++

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report