flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理
  50 随笔 :: 0 文章 :: 0 评论

分析

难度 易

来源

https://leetcode.com/problems/valid-palindrome/

题目

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

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

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

解答

Runtime: 6 ms, faster than 72.53% of Java online submissions for Valid Palindrome.

 1 package LeetCode;
 2 
 3 public class L125_ValidPalindrome {
 4     public boolean isPalindrome(String s) {
 5         s=s.toLowerCase();
 6         if(s.length()<=1)
 7             return true;
 8         int head=0,tail=s.length()-1;
 9         while(head<=tail){
10             if(!Character.isLetterOrDigit(s.charAt(head)))
11             {
12                 head++;
13                 continue;
14             }
15             if(!Character.isLetterOrDigit(s.charAt(tail)))
16             {
17                 tail--;
18                 continue;
19             }
20             if(s.charAt(head)==s.charAt(tail))
21             {
22                 head++;
23                 tail--;
24             }else
25                 return false;
26         }
27         return true;
28     }
29     public static void main(String[] args){
30         L125_ValidPalindrome l125=new L125_ValidPalindrome();
31         String s="A man, a plan, a canal: Panama";
32         //String s="race a car";
33         System.out.println(l125.isPalindrome(s));
34     }
35 }

 

 

posted on 2018-11-06 10:13  flowingfog  阅读(37)  评论(0编辑  收藏