-
Notifications
You must be signed in to change notification settings - Fork 0
/
125.验证回文串.ts
81 lines (80 loc) · 1.67 KB
/
125.验证回文串.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* @lc app=leetcode.cn id=125 lang=typescript
*
* [125] 验证回文串
*
* https://leetcode.cn/problems/valid-palindrome/description/
*
* algorithms
* Easy (46.46%)
* Likes: 626
* Dislikes: 0
* Total Accepted: 459.4K
* Total Submissions: 988.8K
* Testcase Example: '"A man, a plan, a canal: Panama"'
*
* 如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。
*
* 字母和数字都属于字母数字字符。
*
* 给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。
*
*
*
* 示例 1:
*
*
* 输入: s = "A man, a plan, a canal: Panama"
* 输出:true
* 解释:"amanaplanacanalpanama" 是回文串。
*
*
* 示例 2:
*
*
* 输入:s = "race a car"
* 输出:false
* 解释:"raceacar" 不是回文串。
*
*
* 示例 3:
*
*
* 输入:s = " "
* 输出:true
* 解释:在移除非字母数字字符之后,s 是一个空字符串 "" 。
* 由于空字符串正着反着读都一样,所以是回文串。
*
*
*
*
* 提示:
*
*
* 1 <= s.length <= 2 * 10^5
* s 仅由可打印的 ASCII 字符组成
*
*
*/
// @lc code=start
function isPalindrome(s: string): boolean {
const list: string[] = [];
for (let i of s) {
if (/[A-Za-z0-9]/.test(i)) {
list.push(i);
}
}
let left = 0;
let right = list.length - 1;
while (left < right) {
if (list[left].toLowerCase() === list[right].toLowerCase()) {
left += 1;
right -= 1;
}else{
return false;
}
}
return true;
}
// @lc code=end
isPalindrome('race a car');