验证回文串 - 简单
*************
c++
topc:LCR 018. 验证回文串 - 力扣(LeetCode)
*************
Sometime really donnot want to write things just because of donot want to. Make excuses like not feel good or have no time.
Inspect the topic first:
The first question is how to transelate uppercases to lowercases.
So I refer to some of my frienmds and they told me in c++, a standard usage is here
int tolower(int c);
and if you want to turn the letters to uppercases, that is easy:
int toupper(int c);
why need to transform the letters? because in another case here125. 验证回文串 - 力扣(LeetCode)125. 验证回文串 - 如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。字母和数字都属于字母数字字符。给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。 示例 1:输入: s = "A man, a plan, a canal: Panama"输出:true解释:"amanaplanacanalpanama" 是回文串。示例 2:输入:s = "race a car"输出:false解释:"raceacar" 不是回文串。示例 3:输入:s = " "输出:true解释:在移除非字母数字字符之后,s 是一个空字符串 "" 。由于空字符串正着反着读都一样,所以是回文串。 提示: * 1 <= s.length <= 2 * 105 * s 仅由可打印的 ASCII 字符组成https://leetcode.cn/problems/valid-palindrome/
need to transform uppercases and lowercases. the rest of them totally same.
Then I need to pointers i and j. pointrt i travels from left to right. pointer j travels from right to left at the same time. check tolower[i] != tolower[j]. If they say yes everytime, then comes true.
class Solution {
public:
bool isPalindrome(std::string s) {
int i = 0;
int j = s.length() - 1;
// 比较字符,忽略大小写
if (tolower(s[i]) != tolower(s[j])) {
return false;
i++;
j--;
}
return true;
}
};
It cannot run. need to skip the space and punctuation:
class Solution {
public:
bool isPalindrome(string s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
// 跳过非字母数字字符
if (!isalnum(s[i])) {
i++;
continue;
}
if (!isalnum(s[j])) {
j--;
continue;
}
// 比较字符,忽略大小写
if (tolower(s[i]) != tolower(s[j])) {
return false;
}
i++;
j--;
}
return true;
}
};
here, isalnum is a standard library. isalnum library to check if the input is numbers or letters. Think you receive a verifiction code, input the code.
!isalnum(s[j]) This expression checks if s[j] is not an alpha or numeric character. It returns true if s[j] is not an alpha or numeric, and false if it is, and is often used in string processing to skip non-alphanumeric characters.