LeetCode 125. Valid Palindorme (验证回文字符串)

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.

 


题目标签:String, Two Pointers

  题目给了我们一个string s, 让我们判断它是不是 palindorme。

  对于s, 我们只需要比较 字母 和 数字。

       设置一个 left = 0, right = s.length() -1,依次比较,其中遇到任何其他 char 就跳过,具体看code。

  一开始不知道有 Character.isLetterOrDigit() ,还分别用了 letter 和 digit - -

 

Java Solution:

Runtime beats 80.01% 

完成日期:03/07/2017

关键词:two pointers

关键点:skip all non-alphanumeric chars

 1 class Solution 
 2 {
 3     public boolean isPalindrome(String s) 
 4     {
 5         // use two pointers
 6         int left = 0;
 7         int right = s.length() - 1;
 8         
 9         char [] char_arr = s.toCharArray();
10         
11         while(left < right)
12         {
13             while(left < right && !Character.isLetterOrDigit(char_arr[left])) // if char is not letter or digit
14                 left++;
15             
16             while(left < right && !Character.isLetterOrDigit(char_arr[right])) // if char is not letter or digit
17                 right--;
18 
19             if(Character.toUpperCase(char_arr[left]) != Character.toUpperCase(char_arr[right]))
20                 return false;
21             
22             left++;
23             right--;
24         }
25         
26         return true;
27     }
28     
29 
30 }

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

转载于:https://www.cnblogs.com/jimmycheng/p/8845773.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值