-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
day-12-字符串isMatch #12
Comments
此处匹配的定义应该是,判断两个字符串包含内单个字符是否满足一一对应关系 function isMatch(a, b) {
if (typeof a !== "string" || typeof b !== "string") {
console.error('请输入两个字符串')
return
}
if (a.length !== b.length) {
return false
}
// 字符串先拆成数组,再对数组排序,之后判断二者对比是否一致
return a.split("").sort().join("") === b.split("").sort().join("")
} |
function execTimes(call,times) {
// your code
return function(){
console.time()
let begin = Date.now()
for(let i = 0 ; i < times ; i++){
// 与之前不一致,进行修改部分代码
// call(arguments[0] ? arguments[0] : '')
call(...arguments)
}
let end = Date.now()
console.log('执行' + times + '次,耗时' + (end - begin) + 'ms')
console.timeEnd()
}
}
归并排序,快速排序的平均时间复杂度是 |
根据题意,进行优化,做好的办法是不使用排序算法,使用其他方法判断
function isMatch(a, b) {
if (typeof a !== "string" || typeof b !== "string") {
console.error('请输入两个字符串')
return
}
if (a.length !== b.length) {
return false
}
const hash = {}
// 先记录第一个字符串包含的各个元素信息
for (let i = 0; i < a.length; ++i) {
const key = a[i]
if (hash[key]) {
hash[key] += 1
} else {
hash[key] = 1
}
}
for (let j = 0; j < b.length; ++j) {
const key = b[j]
if (!hash[key]) {
return false
} else {
hash[key] -= 1
}
}
return true
} |
请用
JavaScript
实现一个方法,该方法能够判断两个字符串是否 匹配,如:使用上一章节的
execTimes
方法测试你的方案执行10000次的时长,该方案是否是最优方案?如果不是,请给出最优方法,并说明时间复杂度The text was updated successfully, but these errors were encountered: