gpt4 book ai didi

javascript - 为什么相同字符不相邻时输出不正确?

转载 作者:行者123 更新时间:2023-11-28 12:12:08 25 4
gpt4 key购买 nike

等值图是没有重复字母(连续或不连续)的单词。实现一个函数来确定仅包含字母的字符串是否为等值线图。假设空字符串是等值线图。忽略字母大小写。

function isIsogram(str){
let NewStr = str.toLowerCase();
for ( let i = 0; i < NewStr.length; i++){
for ( let j = i + 1; j < NewStr.length; j++) {
if ( NewStr[i] === NewStr[j]) {
return false }
else {
return true}
}
}
}

最佳答案

一旦发现两个字母不相等,此代码将返回true:

if ( NewStr[i] === NewStr[j]) {
return false }
else {
return true}

您应该做的是仅在条件通过时返回false。如果不继续循环,最后返回true:

function isIsogram(str) {
let NewStr = str.toLowerCase();
for (let i = 0; i < NewStr.length; i++) {
for (let j = i + 1; j < NewStr.length; j++) {
if (NewStr[i] === NewStr[j]) {
return false
}
}
}

return true;
}

console.log(isIsogram('cdba')); // true
console.log(isIsogram('aa')); // false
console.log(isIsogram('efgaba')); // false

您还可以使用 Set 进行相同的检查。 。如果 Set 中的字母数等于原始字符串中的字母数,则所有字符都是唯一的。

function isIsogram(str) {
return new Set(str.toLowerCase()).size === str.length;
}

console.log(isIsogram('cdba')); // true
console.log(isIsogram('aa')); // false
console.log(isIsogram('efgaba')); // false

关于javascript - 为什么相同字符不相邻时输出不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com