Created
April 19, 2026 17:22
-
-
Save thinkphp/761a6f5191180fda88b1f6355d4e98fb to your computer and use it in GitHub Desktop.
Leetcode valid palindrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public boolean isPalindrome(String s) { | |
| StringBuilder tmp = new StringBuilder(); | |
| //Time Complexity: O(n) | |
| for(char c: s.toCharArray()) { | |
| if(Character.isLetterOrDigit(c)) { | |
| tmp.append(Character.toLowerCase(c)); | |
| } | |
| } | |
| //Time Complexity O(n) | |
| int n = tmp.length(); | |
| for(int i = 0; i < n/2; i++) { | |
| if(tmp.charAt(i) != tmp.charAt(n-i-1)) return false; | |
| } | |
| //amanaplanacanalpanama //based-0 index | |
| //0 | |
| return true; | |
| } | |
| public static void main(String[] args) { | |
| Solution sol = new Solution(); | |
| System.out.println(sol.isPalindrome("A man, a plan, a canal: Panama")); //TRUE | |
| System.out.println(sol.isPalindrome("Race a Car")); //FALSE | |
| } | |
| } | |
| //A man, a plan, a canal: Panama | |
| //tmp.add(a) | |
| //tmp.add(m) | |
| //tmp.add(a) | |
| //tmp.add(n) | |
| //tmp.add(a) | |
| //tmp.add(p) | |
| //tmp.add(l) | |
| //tmp.add(a) | |
| //tmp.add(n) | |
| //tmp.add(a) | |
| //tmp.add(c) | |
| //tmp.add(a) | |
| //tmp.add(n) | |
| //tmp.add(a) | |
| //tmp.add(l) | |
| //tmp.add(p) | |
| //tmp.add(a) | |
| //tmp.add(n) | |
| //tmp.add(a) | |
| //tmp.add(m) | |
| //tmp.add(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment