Leetcode : 125. Valid Palindrome

cloudAndTechnology
1 min readJun 18, 2021

Company : Facebook, Microsoft

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

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.

Constraints:

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

Solution :

Runtime: 3 ms, faster than 69.49% of Java online submissions for Valid Palindrome.

Memory Usage: 39.3 MB, less than 52.07% of Java online submissions for Valid Palindrome.

Program :

class Solution {
public boolean isPalindrome(String s) {
int i=0;
s=s.toLowerCase();
int j=s.length()-1;

if(s.length()==1) return true;

while(i<j){
while(i<j && !Character.isLetterOrDigit(s.charAt(i))){
i++;

}
while(i<j && !Character.isLetterOrDigit(s.charAt(j)))
j — ;

if(s.charAt(i) == s.charAt(j)){
i++;
j — ;
}
else return false;

}
return true;
}
}

--

--