Topic description
Given a string, verify that it is a palindrome, considering only alphanumeric characters, ignoring case of letters.
Explanation: In this problem, we define the empty string as a valid palindrome.
Example 1:
输入: "A man, a plan, a canal: Panama"
输出: true
解释:"amanaplanacanalpanama" 是回文串
Example 2:
输入: "race a car"
输出: false
解释:"raceacar" 不是回文串
Likou original title address: https://leetcode.cn/problems/valid-palindrome/
solution
Scheme 1: Determine whether item --- i
and item j
are equal (i+j==s.length-1)
In the code below, I do not distinguish between i
and j
, it is directly i
and (filterS.length - 1) - i
var isPalindrome = function (s) {
let flag = true
// 先加工数据,替换去掉空格特殊符号,以及转成小写英文统一对比
let filterS = s.replace(/[^A-Za-z0-9]/g, '').toLocaleLowerCase()
for (let i = 0; i < filterS.length; i++) {
// 如果有其中一项不符合规则,就直接结束循环,返回结果即可
if (filterS[i] != filterS[filterS.length - 1 - i]) {
flag = false
return flag
}
}
// 最后再返回一下,因为有可能就是回文数,要返回true
return flag
};
Note that the loop in the code does not actually need to loop all the items, only half of the loop is needed, so the above code can also be written differently:
for (let i = 0; i < Math.trunc(filterS.length / 2); i++) {......}
Note that Math.trunc() of the unpopular api means rounding
-
Math.trunc(2.5) // 2
-
Math.trunc(3) // 3
UsingMath.trunc()
only half the loop consumes less memory, but it will take more time, becauseMath公式
will also take time
Scheme 2 String to Array Reversal Comparison
var isPalindrome = function (s) {
// 先加工数据,去掉空格特殊符号,以及转成小写英文统一对比
let filterS = s.replace(/[^A-Za-z0-9]/g, '').toLocaleLowerCase()
let filterSArr = filterS.split('') // 转成正常顺序数组
let filterSArrReverse = filterS.split('').reverse() // 转成倒叙顺序数组
if (JSON.stringify(filterSArr) == JSON.stringify(filterSArrReverse)) { // 比较是否相等
return true
} else {
return false
}
};
Although this method can also be implemented, the performance is not good, because 数组的方法反转
and JSON序列化
are also time-consuming.
Summarize
Under normal circumstances, we use space for time, which consumes a little more memory, but it is still cost-effective to speed up the time. So option 1 is the first choice
Attached is a regular, only Chinese and English numbers can be entered str = str.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。