The title
LeetCode 第 125. Verify the palindrome string association type: string, double pointer
Given a string, verify that it is a palindrome string, considering only alphanumeric characters, regardless of letter case. Note: In this case, we define an empty string as a valid palindrome string. Example 1: Enter "A man, A plan, A canal: Panama" Output: true Example 2: enter "race A car" Output: falseCopy the code
Time to solve the problem.
class Solution {
public boolean isPalindrome(String s) {
}
}
Copy the code
The method input parameters are given above to complete the answer.
Subject analysis
- In this case, two methods are used
- The first way is to build a new string, remove all the symbolic whitespace, and then invert the new string
- The second way is to use double Pointers, double Pointers for comparison
Answers to analysis
This article only analysis I do the idea, only for reference, to understand a solution to the idea, other kinds of ideas to do the problem please access the Internet.
Plan a
Answer successful: Execution time :7 ms, beating 20.67% of Java users memory consumption :38.6 MB, beating 41.07% of Java users
class Solution { public boolean isPalindrome(String s) { StringBuilder sb = new StringBuilder(); // Construct a new string for (int I = 0; i < s.length(); i++) { if (Character.isLetterOrDigit(s.charAt(i))) { sb.append(s.charAt(i)); }} String a = sb.toString(); String b = sb.reverse().toString(); If (a.qualsignorecase (b)) {return true; } else { return false; }}}Copy the code
Scheme 2
Answer successful: Execution time :3 ms, beat 93.63% of Java users memory consumption :38.3 MB, beat 91.92% of Java users
class Solution { public boolean isPalindrome(String s) { int low = 0, high = s.length() - 1; While (low < high) {// The left pointer is less than the right pointer loop continues if (! Character.isLetterOrDigit(s.charAt(low))) { low++; } else if (! Character.isLetterOrDigit(s.charAt(high))) { high--; Else {if (character.tolowerCase (s.charat (low))== character.tolowerCase (s.charat (high))) {// Two Pointers have the same Character low++; high--; } else {// return false; } } } return true; }}Copy the code