简体   繁体   中英

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. 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:

 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:

 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):

 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'). 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')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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