最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check for characters in a string being unique - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Apr 3, 2019 at 11:13 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Apr 3, 2019 at 5:35 user3763875user3763875 3292 silver badges11 bronze badges 1
  • FWIW: function noDuplicatedChars() { const chars = new Set(); for (let c of str) { if (chars.has(c)) return false; chars.add(c);} return true; } is a faster alternative. – Frax Commented Apr 3, 2019 at 5:55
Add a comment  | 

2 Answers 2

Reset to default 25

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 (

发布评论

评论列表(0)

  1. 暂无评论