Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit767ebf8

Browse files
Update 125-Valid-Palindrome.js
refactor: simplify two pointer solution to make more readable
1 parent43119ae commit767ebf8

File tree

1 file changed

+21
-41
lines changed

1 file changed

+21
-41
lines changed

‎javascript/125-Valid-Palindrome.js

Lines changed: 21 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -31,47 +31,27 @@ const reverse = (s) => s
3131
*@return {boolean}
3232
*/
3333
varisPalindrome=function(s){
34-
if(!s.length)returntrue;
35-
36-
returnisValid(s);/* Time O(N) */
37-
};
38-
39-
constisValid=(s)=>{
40-
let[left,right]=[0,(s.length-1)];
41-
42-
while(left<right){/* Time O(N) */
43-
[left,right]=moveToMid(s,left,right);/* Time O(N) */
44-
45-
const[leftCode,rightCode]=getCodes(s,left,right);
46-
47-
constisEqual=leftCode===rightCode;
48-
if(!isEqual)returnfalse;
49-
50-
left++;right--;
34+
if(s.length<=1)returntrue;
35+
36+
let[left,right]=[0,s.length-1];
37+
letleftChar,rightChar;
38+
while(left<right){
39+
leftChar=s[left];
40+
rightChar=s[right];
41+
42+
// skip char if non-alphanumeric
43+
if(!/[a-zA-Z0-9]/.test(leftChar)){
44+
left++;
45+
}elseif(!/[a-zA-Z0-9]/.test(rightChar)){
46+
right--;
47+
}else{
48+
// compare letters
49+
if(leftChar.toLowerCase()!=rightChar.toLowerCase()){
50+
returnfalse;
51+
}
52+
left++;
53+
right--;
54+
}
5155
}
52-
5356
returntrue;
54-
}
55-
56-
constmoveToMid=(s,left,right)=>{
57-
while((left<right)&&!isAlphaNumeric(s[left]))left++;/* Time O(N) */
58-
while((left<right)&&!isAlphaNumeric(s[right]))right--;/* Time O(N) */
59-
60-
return[left,right];
61-
}
62-
63-
constgetCodes=(s,left,right)=>[getCode(s[left]),getCode(s[right])];
64-
65-
constgetCode=(char)=>char.toLowerCase().charCodeAt(0);
66-
67-
constisAlphaNumeric=(char)=>{
68-
constcode=getCode(char);
69-
70-
const[a,z]=[97,122];
71-
constisAlpha=(a<=code)&&(code<=z);
72-
73-
const[zero,nine]=[48,57];
74-
constisNumeric=(zero<=code)&&(code<=nine);
75-
76-
returnisAlpha||isNumeric;
7757
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp