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.
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
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
use .match() function for each of the character. calculate occurrences using length. Guess thats it.
(str.match(/yourChar/g) || []).length
You are using arr[str.charCodeAt(i)]
which is wrong. It should be arr[str[i].charCodeAt(0)]
var arr = [];
var str="abcdefgh";
for (i=0;i<255;i++){
arr[i]=false;
}
function check(){
for (i=0;i<str.length;i++){
if (arr[str[i].charCodeAt(0)]==true){
return false;
}
arr[str[i].charCodeAt(0)]=true;
}
console.log(arr);
return true;
}
check();
Time complexity = O(n) Space complexity = O(n)
const isUnique = (str) => {
let charCount = {};
for(let i = 0; i < str.length; i++) {
if(charCount[str[i]]){
return false;
}
charCount[str[i]] = true;
}
return true;
}
const isUniqueCheekyVersion = (str) => {
return new Set(str).size === str.length;
}
Solution 3: Transform string to chars array, sort them and then loop through them to check the adjacent elements, if there is a match return false else true
Solution 4: It's similar to Solution 1 except that we use a Set data structure which is introduced in recent versions of javascript
// no additional Data structure is required. we can use naive solution // Time Complexity:O(n^2) function isUnique(str) { for (let i = 0; i < str.length; i++) { for (let j = 1 + i; j < str.length; j++) { if (str[i] === str[j]) { return false; } } } return true; } // if you can use additional Data structure // Time Complexity:O(n) function isUniqueSecondMethos(str) { let dup_str = new Set(); for (let i = 0; i < str.length; i++) { if (dup_str.has(str[i])) { return false; } dup_str.add(str[i]); } return true; } console.log(isUniqueSecondMethos('hello'));
Use an object as a mapper
function uniqueCharacterString(inputString) {
const characterMap = {};
let areCharactersUnique = true;
inputString.trim().split("").map((ch)=>{
if(characterMap[ch]===undefined) {
characterMap[ch] = 1;
} else {
areCharactersUnique = false;
}
})
return areCharactersUnique;
}
Algo
*1. step -first string is ->stack *
*2.step-string covert to CharArray *
3. step - use iteration in array ['s','t','a','c','k']
4. step - if(beginElement !== nextElement){return true}else{return false}
Implement code
function uniqueChars(string){
var charArray = Array.from(string) //convert charArray
for(var i=0;i<charArray.length;i++){
if(charArray[i] !== charArray[i+1]){
return true
}
else{
return false
}
}
}
var string ="stack"
console.log(uniqueChars(string))
Time complexity O(nlogn)
We can also try using indexOf
and lastIndexOf
method:
function stringIsUnique(input) {
for (i = 0; i < input.length; i++) {
if (input.indexOf(input[i]) !== input.lastIndexOf(input[i])) {
return false;
}
}
return true;
}
Algo
'Mozilla'
will returns Object{ M: 1, o: 1, z: 1, i: 1, l: 2, a: 1 }
. Note that, the bitwise NOT operator (~) on -~undefined
is 1
, -~1
is 2
, -~2
is 3
etc.true
when all occurrences appear only once .Implement code
var isUnique = (str) => { const hash = {}; for (const key of str) { hash[key] = -~hash[key]; } return Object.values(hash).every((t) => t === 1); }; console.log(isUnique('Mozilla')); console.log(isUnique('Firefox'));
Another alternative could be:
var isUnique = (str) => { const hash = {}; for (const i in str) { if (hash[str[i]]) return false; hash[str[i]] = true; } return true; }; console.log(isUnique('Mozilla')); console.log(isUnique('Firefox'));
To make efficient one, you can use simple hash map
let isUnique = (s) => { let ar = [...s]; let check = {}; for (let a of ar) { if (!check[a]) { check[a] = 1; } else { return false } } return true; } alert("isUnique : "+isUnique("kailu"));
Time complexity & Space complexity
using ES6
let isUnique = (s)=>{ return new Set([...s]).size == s.length; } console.log("using ES6 : ",isUnique("kailu"));
We can use split method of string:
const checkString = (str) => {
let isUniq = true;
for (let i = 0; i < str.length; i++) {
if (str.split(str[i]).length > 2) {
isUniq = false;
break;
}
}
return isUniq;
};
console.log(checkString("abcdefgh")); //true
console.log(checkString("aa")); //false
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.