LeetCode 125. Valid Palindrome

本文详细解析了LeetCode第125题“Valid Palindrome”的解决方案,介绍了如何通过忽略非字母数字字符并进行大小写转换来判断字符串是否为回文。代码实现使用Java语言,分享了一种高效且简洁的方法。

分析

难度 易

来源

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 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/flowingfog/p/9913647.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值