![](/img/trans.png)
[英]Check if a string is composed of all unique characters— not equal to operator in JavaScript
[英]Checking if the characters in a string are all unique
我試圖通過使用數組來使用 JS 解決這個問題。
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;
}
我正在初始化一個固定大小為 256 的數組,使其具有布爾值false
。 然后我將字符串中字符的相應 ASCII 索引的值設置為 true。 如果我再次找到相同的字符,我將返回false
。
在運行程序時,即使字符串沒有任何重復字符,我也會返回 false。
用所有字符填充Set
並將其大小與字符串的長度進行比較:
function isUnique(str) { return new Set(str).size == str.length; } console.log(isUnique('abc')); // true console.log(isUnique('abcabc')); // false
使用對象以獲得更快的結果
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
對每個字符使用 .match() 函數。 使用長度計算出現次數。 猜猜就是這樣。
(str.match(/yourChar/g) || []).length
您正在使用arr[str.charCodeAt(i)]
這是錯誤的。 它應該是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();
時間復雜度 = O(n) 空間復雜度 = 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;
}
解決方案3:將字符串轉換為字符數組,對它們進行排序,然后遍歷它們以檢查相鄰元素,如果匹配則返回false else true
解決方案 4:它類似於解決方案 1,不同之處在於我們使用了最新版本的 javascript 中引入的 Set 數據結構
// 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'));
使用對象作為映射器
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;
}
算法
*1. step -first 字符串是 ->stack *
*2.step-string 轉換為 CharArray *
3. step - 在數組 ['s','t','a','c','k'] 中使用迭代
4. step - if(beginElement !== nextElement){return true}else{return false}
實現代碼
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))
時間復雜度O(nlogn)
我們也可以嘗試使用indexOf
和lastIndexOf
方法:
function stringIsUnique(input) {
for (i = 0; i < input.length; i++) {
if (input.indexOf(input[i]) !== input.lastIndexOf(input[i])) {
return false;
}
}
return true;
}
算法
'Mozilla'
將返回Object{ M: 1, o: 1, z: 1, i: 1, l: 2, a: 1 }
。 請注意, -~undefined
上的按位非運算符(~)是1
, -~1
是2
, -~2
是3
等等。true
。實現代碼
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'));
另一種選擇可能是:
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'));
為了提高效率,您可以使用簡單的哈希映射
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"));
時間復雜度和空間復雜度
使用 ES6
let isUnique = (s)=>{ return new Set([...s]).size == s.length; } console.log("using ES6 : ",isUnique("kailu"));
我們可以使用字符串的 split 方法:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.