简体   繁体   English

检查字符串中的字符是否唯一

[英]Check for characters in a string being unique

I implemented my algorithm for checking if the string passed in is unique. 我实现了我的算法来检查传入的字符串是否唯一。 I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. 我觉得我的算法是正确的,但显然在某些情况下它会给出错误的结果。 Why? 为什么?

 function isUnique(str) { let sortedArr = str.split('').sort(); for (let [i, char] of sortedArr.entries()) { if (char === sortedArr[i + 1]) { return false } else { return true } } } console.log(isUnique('heloworld')) // true 

return immediately terminates the function, so only the first iteration if your for loop will ever run. return立即终止函数,因此只有第一次迭代才会运行for循环。 Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop: 相反,您应检查所有字符是否唯一(如果不是,在循环内return false ),否则在循环结束后return true

 function isUnique(str) { let sortedArr = str.split('').sort(); for(let [i,char] of sortedArr.entries()) { if(char === sortedArr[i + 1]) { return false } } return true } console.log(isUnique('heloworld')) 

But it would probably be a lot easier to use a Set , and see if its size is equal to the length of the string: 但是使用Set可能会容易Set ,并查看它的大小是否等于字符串的长度:

 function isUnique(str) { return new Set(str).size === str.length; } console.log(isUnique('heloworld')) console.log(isUnique('abc')) 

See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points ( 𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters): 请参阅评论,感谢Patrick:如果您需要考虑由多个UCS-2代码点组成的字符( 𝟙𝟚𝟛😎😜🙃等),请调用字符串迭代器并检查它返回的项目数,可以使用spread或Array.from来完成Array.from (因为否则, str.length将不会评估为正确的单个字符数):

 function isUnique(str) { return new Set(str).size === [...str].length; } console.log(isUnique('😜')); console.log(isUnique('😜😜')); 

Only first iteration in your for loop is run (because you always execute 'return'). 只运行for循环中的第一次迭代(因为你总是执行'return')。 Instead you can use following code 相反,您可以使用以下代码

 function isUnique(str, t={}) { return ![...str].some(c=> t[c]=c in t) } console.log('heloworld =>',isUnique('heloworld')); console.log('helo =>',isUnique('helo')); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM