125. Valid Palindrome
Published in
1 min readJul 19, 2023
Easy
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.
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.
Solution:
Approach 1:
class Solution {
public boolean isPalindrome(String s) {
String str = s.toLowerCase().replaceAll("[^a-z0-9]","");
int i = 0;
int j = str.length()-1;
while(j>=i){
if(str.charAt(i) != str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}
Approach 2:
class Solution {
public boolean isPalindrome(String s) {
String user_string = "";
String reverse_string = "";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)>='a' && s.charAt(i) <='z' || s.charAt(i)>='A' && s.charAt(i) <='Z' || s.charAt(i)>= '0' && s.charAt(i) <='9')
{
user_string = user_string + Character.toLowerCase(s.charAt(i));
}
}
for(int j=user_string.length()-1;j>=0;j--){
reverse_string = reverse_string + user_string.charAt(j);
}
if(user_string.equals(reverse_string))
return true;
return false;
}
}