Determine whether the character is unique

 Determine whether the character is unique

Implement an algorithm to determine whether all characters of a string s are all different.

Example 1:

  • Input: s = "leetcode"
  • Output: false 

Example 2:

  • Input: s = "abc"
  • Output: true

Sample code:

class Solution(object):
    def isUnique(self, astr):
        """
        :type astr: str
        :rtype: bool
        """
        astr_set = set(astr)
        if len(astr) == len(astr_set):
            return True
        else:
            return False


a = Solution()
# b = a.isUnique('abcdd')
b = a.isUnique('abcdef')
print(b)

running result:

Problem-solving ideas:

 

  • Convert string to list
  • Use the built-in function set() to convert a string to a collection, and the collection will automatically exclude duplicates.
  • After that, the list is converted into a collection, and the length is judged by the non-repeatability of the collection elements.
  • If there are duplicate elements, they will be removed and the length will be changed

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/113843700