1. 字符串?dāng)?shù)組去重
const array = ['z', 'q', 'y', 'z', 'a', 'b', 'a'];
// ES6 set 去重
function unrepeated_1(arr) {
return [...new Set(arr)]
// return Array.from(new Set(arr))
}
// 利用對象鍵名唯一 去重
function unrepeated_2(arr) {
const obj = {};
for (let i = arr.length; i--;) {
obj[arr[i]] = ''
}
return Object.keys(obj)
}
console.log(
unrepeated_1(array),
unrepeated_2(array)
)
2. 判斷一個(gè)字符串是否回文(左右對稱)
const string = 'heroreh'; // qaq
function isLM_1(str) {
return str.split('').reverse().join('') === str
}
function isLM_2(str) {
let s = '';
for (let i = str.length; i--;) {
s += str[i]
}
return s === str
}
function isLM_3(str) {
const len = str.length;
for (let i = len; i--;) {
if (str[i] !== str[len - 1 - i]) {
return false
}
if (i < str.length / 2) {
return true
}
}
}
console.log(
isLM_1(string),
isLM_2(string),
isLM_3(string)
)