码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Valid Palindrome

时间:2015-05-18 18:46:26      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:

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

Valid Palindrome

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.

 


 

两个指针,一个指向头,一个指向尾。如果不是字母数字,就继续找,头++尾--,然后比较值就好啦。

没交的时候看到这道题有Solution,考虑了很久有没有其他机智的办法。等交了一看,其实并没有,一切都是错觉。

 1 /**
 2  * @param {string} s
 3  * @return {boolean}
 4  */
 5 var isPalindrome = function(s) {
 6     s = s.trim();
 7     if(s === ""){
 8         return true;
 9     }else{
10         var i = 0, j = s.length - 1;
11         while(i <= j){
12             while(!/[a-z0-9]/i.test(s[i]) && i < s.length && i < j){
13                 i++;
14             }
15             while(!/[a-z0-9]/i.test(s[j]) && j > 0 && i < j){
16                 j--;
17             }
18             
19             if(s[i].toUpperCase() !== s[j].toUpperCase()){
20                 return false;
21             }
22             
23             i++; j--;
24         }
25         
26         i--; j++;
27         if(i !== j && s[i].toUpperCase() !== s[j].toUpperCase()){
28             return false;
29         }
30         
31         return true;
32     }
33 };

 

 

 

[LeetCode][JavaScript]Valid Palindrome

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4512458.html

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