Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Determines if a character is unique
Example 1:
Input: s = “leet code” Output: false Example 2: Input: s = “ABC” Output: true
Limitations:
< 1 >
0 <= len(s) <= 100
< 2 >
Bonus points if you don’t use extra data structures.
Solution 1 Iterates through the string to determine where a character appears
Memory consumption is 37.5MB
/** * @param {string} astr * @return {Boolean} */ var isUnique = function(astr) // The second indexOf gets the first occurrence of the specified character. i<=astr.length; i++){ //if(astr.indexOf(astr[i], astr.indexOf(astr[i])+1)! For (let I of astr) {if (astr.indexof (I)){if (astr.indexof (I)! == astr.lastIndexOf(i)) { return false } } return true };Copy the code
Solution 2 uses Set in ES6
Set
The Set object allows you to store a unique value of any type, either a primitive value or an object reference.
Special values
- +0 and -0 are identical in the storage of judgment uniqueness, so they are not repeated;
- Undefined and undefined are identical, so do not repeat;
- NaN is not identical to NaN, but only one can be stored in a Set.
The results of
Execution time: 80ms
Memory consumption is 37.5MB
/**
* @param {string} astr
* @return {boolean}
*/
var isUnique = function(astr) {
return new Set([...astr]).size === astr.length
};
Copy the code
Thank you very much for the handsome and beautiful people who can see this. If this article is good or helpful to you, please like it, pay attention to it and share it. Of course, if you have any questions, please comment and discuss them