DEV Community

Cover image for Leetcode — Top Interview 150–125. Valid Palindrome
Ben Pereira
Ben Pereira

Posted on

Leetcode — Top Interview 150–125. Valid Palindrome

It’s an easy problem with description being:

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.

Following what’s a palindrome, you basically remove all non-alpha then call to lower the case method and make a revert to compare.

Using methods and a bit of reg exp you can solve this in 3 lines:

class Solution {
    public boolean isPalindrome(String s) {
        final String reduced = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
        final String inverted = new StringBuilder(reduced).reverse().toString();
        return reduced.equals(inverted);
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 15 ms, faster than 22.51% of Java online submissions for Valid Palindrome.

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

That should be enough as simple and easy question, but to have it better performance you could iterate and check each char and remove and adapt as needed, for this case checkout saksham answer on leetcode (if you wish me to explain in details, please comment down bellow).

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more