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

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

LeetCode: Valid Palindrome   解题报告

SOLUTION 1:

左右指针往中间判断。注意函数: toLowerCase

 1 /*
 2     SOLUTION 1: Iterator.
 3     */
 4     public boolean isPalindrome1(String s) {
 5         if (s == null) {
 6             return false;
 7         }
 8         
 9         int len = s.length();
10         
11         boolean ret = true;
12         
13         int left = 0;
14         int right = len - 1;
15         
16         String sNew = s.toLowerCase();
17         
18         while (left < right) {
19             // bug 1: forget a )
20             while (left < right && !isNumChar(sNew.charAt(left))) {
21                 left++;
22             }
23             
24             while (left < right && !isNumChar(sNew.charAt(right))) {
25                 right--;
26             }
27             
28             if (sNew.charAt(left) != sNew.charAt(right)) {
29                 return false;
30             }
31             
32             left++;
33             right--;
34         }
35         
36         return true;
37     }
38     
39     public boolean isNumChar(char c) {
40         if (c <= '9' && c >= '0' || c <= 'z' && c >= 'a' || c <= 'Z' && c >= 'A') {
41             return true;
42         }
43         
44         return false;
45     }
View Code

相关文章:

  • 2021-08-27
  • 2022-02-24
  • 2022-02-13
  • 2021-10-09
  • 2022-12-23
  • 2022-03-04
  • 2021-10-19
  • 2022-01-30
猜你喜欢
  • 2021-07-17
  • 2022-12-23
  • 2021-08-28
  • 2021-08-05
  • 2022-12-23
  • 2021-12-27
  • 2021-10-25
相关资源
相似解决方案