Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the characters in a string are all unique

Tags:

javascript

I am trying to solve this problem using JS by just using an array.

var str = 'abcdefgh';

for (i = 0; i < 255; i++) {
  arr[i] = false;
}

function check() {
  for (i = 0; i < str.length; i++) {
    if (arr[str.charCodeAt(i)] == true) {
      return false;
    }
    arr[str.charCodeAt(i)] = true;
  }
  return true;
}

I am initializing an array of fixed size 256 to have the boolean value false. Then i am setting the value for the corresponding ASCII index to true for characters in the string. And if i find the same character again, i am returning false.

While running the program, i am getting false returned even if the string doesn't have any duplicate characters.

like image 436
Santhiya Avatar asked Nov 27 '22 16:11

Santhiya


2 Answers

Fill a Set with all characters and compare its size to the string's length:

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

console.log(isUnique('abc'));    // true
console.log(isUnique('abcabc')); // false
like image 132
le_m Avatar answered Dec 05 '22 01:12

le_m


Use object for faster result

function is_unique(str) {
  var obj = {};
  for (var z = 0; z < str.length; ++z) {
    var ch = str[z];
    if (obj[ch]) return false;
    obj[ch] = true;
  }
  return true;
}

console.log(is_unique("abcdefgh")); // true
console.log(is_unique("aa")); // false
like image 42
Kokizzu Avatar answered Dec 05 '22 02:12

Kokizzu