Leetcode Study Day 13

Valid Palindrome

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.


Constraints:

1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.

My solution

My solution is convert all uppercase letters to lowercase, meanwhile, remove all non-alphanumeric characters by comparing the ASCII Value. Then, we use two pointers to check if the string is a palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool isPalindrome(string s) {
string answer = "";
// tolower() is a string to transform all uppercase letters to lowercase
for (int i = 0; i < s.size(); i++){
// ASCII Value of uppercase letters is from 65 to 90
if (s[i] >= 65 && s[i] <= 90)
answer += tolower(s[i]);
// ASCII Value of lowercase letters is from 97 to 122 and the ASCII Value of numbers is from 48 to 57
else if ( s[i] >= 97 && s[i] <= 122 || s[i] >= 48 && s[i] <= 57)
answer += s[i];
}
int j = answer.size() - 1;
for (int i = 0; i <= j ; i++){
if (answer[i] != answer[j])
return false;
j --;
}
return true;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信