LeetCode 125: Valid Palindrome Solution
Master LeetCode problem 125 (Valid Palindrome), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
125. Valid Palindrome
Problem Explanation
Explanation
To solve this problem, we can use two pointers approach. We iterate through the string from both ends, moving towards the center, and compare alphanumeric characters. We skip non-alphanumeric characters during comparison. If at any point the characters don't match, we return false. If the loop completes without returning false, then the string is a valid palindrome.
- Time complexity: O(n) where n is the length of the input string
- Space complexity: O(1)
Solution Code
class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
char lChar = Character.toLowerCase(s.charAt(left));
char rChar = Character.toLowerCase(s.charAt(right));
if (!Character.isLetterOrDigit(lChar)) {
left++;
} else if (!Character.isLetterOrDigit(rChar)) {
right--;
} else {
if (lChar != rChar) {
return false;
}
left++;
right--;
}
}
return true;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 125 (Valid Palindrome)?
This page provides optimized solutions for LeetCode problem 125 (Valid Palindrome) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 125 (Valid Palindrome)?
The time complexity for LeetCode 125 (Valid Palindrome) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 125 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 125 in Java, C++, or Python.