码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Palindrome

时间:2016-07-10 23:15:57      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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

 Notice

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.

Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

分析:

两个指针指向前后两端,如果指向的值不是alphanumeric characters,向前/后走。

 1 public class Solution {
 2     /**
 3      * @param s A string
 4      * @return Whether the string is a valid palindrome
 5      */
 6     public boolean isPalindrome(String s) {
 7         if(s == null || s.length() <= 1) return true;
 8         
 9         int i = 0;
10         int j = s.length() - 1;
11         
12         s = s.toLowerCase();
13         
14         while (i < j) {
15             while(i < s.length() && !(s.charAt(i) <= Z && s.charAt(i) >= A || s.charAt(i) <= z && s.charAt(i) >= a || s.charAt(i) <= 9 && s.charAt(i) >= 0)) {
16                 i++;
17             }
18             while(j >= 0 && !(s.charAt(j) <= Z && s.charAt(j) >= A || s.charAt(j) <= z && s.charAt(j) >= a || s.charAt(j) <= 9 && s.charAt(j) >= 0)) {
19                 j--;
20             }
21             
22             if (i < j) {
23                 if (s.charAt(i) == s.charAt(j)) {
24                     i++;
25                     j--;
26                 } else {
27                     return false;
28                 }
29             }
30         }
31         return true;
32     }
33 }

 

 

Valid Palindrome

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5658775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!