美文网首页
[python] 2019-02-18

[python] 2019-02-18

作者: 原来是酱紫呀 | 来源:发表于2019-02-18 20:05 被阅读0次

    .711. Jewels and Stones
    .929. Unique Email Addresses
    .709. To Lower Case
    .804. Unique Morse Code Words

    notes:
    collections.Counter(S)
    set(),创建一个无序不重复元素集


    771. Jewels and Stones

    1) 题目描述:

    You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

    The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

    Example 1:

    Input: J = "aA", S = "aAAbbbb"
    Output: 3

    Example 2:

    Input: J = "z", S = "ZZ"
    Output: 0

    Note:

    S and J will consist of letters and have length at most 50.
    The characters in J are distinct.

    2) CODE

    数组count

    因为J里的元素是独一无二的,所以只要数一数S中出现了多少个j就行了。不需要用set().

    时间复杂度是O(MN),空间复杂度是O(1)。M是J长度,N是S长度。

    class Solution(object):
        def numJewelsInStones(self, J, S):
            """
            :type J: str
            :type S: str
            :rtype: int
            """
            return sum(S.count(j) for j in J)
    

    字典Counter

    先用Counter保存每个字母出现的次数,然后由于J里面的字符是不重复的,所以直接遍历,然后统计其中的每个字符在S中出现的次数就行了。

    时间复杂度是O(MN),空间复杂度是O(N)。M是J长度,N是S长度。

    class Solution:
        def numJewelsInStones(self, J, S):
            """
            :type J: str
            :type S: str
            :rtype: int
            """
            sCount = collections.Counter(S)
            res = 0
            for j in J:
                res += sCount[j]
            return res
    
    

    929. Unique Email Addresses

    1) 题目

    Every email consists of a local name and a domain name, separated by the @ sign.

    For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.

    Besides lowercase letters, these emails may contain '.'s or '+'s.

    If you add periods (’.’) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)

    If you add a plus (’+’) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)

    It is possible to use both of these rules at the same time.

    Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?

    Example 1:

    Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
    Output: 2
    Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually

    Note:

    1 <= emails[i].length <= 100
    1 <= emails.length <= 100
    Each emails[i] contains exactly one ‘@’ character.

    2) CODE

    class Solution:
        def numUniqueEmails(self, emails: 'List[str]') -> 'int':
            """
            :type emails: List[str]
            :rtype: int
            """
            dic = {}
            for i in emails:
                e = i.split('@')
                e[0] = e[0].replace('.','')
                if '+' in e[0]:
                    e[0] = e[0][:e[0].index('+')]
                if e[0] + '@' +  e[1] not in dic:
                    dic[e[0] + '@' +  e[1]] = 1
            #print dic
            return len(dic)
    
            seen = set()
            for email in emails:
                local, domain = email.split('@')
                if '+' in local:
                    local = local[:local.index('+')]
                seen.add(local.replace('.','') + '@' + domain)
            return len(seen)
    

    709. To Lower Case

    1) 题目

    Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

    Example 1:

    Input: "Hello"
    Output: "hello"

    Example 2:

    Input: "here"
    Output: "here"

    Example 3:

    Input: "LOVELY"
    Output: "lovely"

    2) CODE

    class Solution:
        def toLowerCase(self, str: 'str') -> 'str':
            '''
            str: str
            rtype: str
            '''
            return str.lower()
    

    804. Unique Morse Code Words

    1) 题目

    International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.

    For convenience, the full table for the 26 letters of the English alphabet is given below:

    [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-.-....-", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.

    Return the number of different transformations among all words we have.

    Example:

    Input: words = ["gin", "zen", "gig", "msg"]

    Output: 2
    Explanation:
    The transformation of each word is:
    "gin" -> "--...-."
    "zen" -> "--...-."
    "gig" -> "--...--."
    "msg" -> "--...--."
    There are 2 different transformations, "--...-." and "--...--.".

    Note:

    The length of words will be at most 100.
    Each words[i] will have length in range [1, 12].
    words[i] will only consist of lowercase letters.

    2) CODE

    class Solution:
        def uniqueMorseRepresentations(self, words: 'List[str]') -> 'int':
            '''
            words: List[str]
            rtype: int
            '''
            Morse=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
            Letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    
            for i in range(len(words)):
                temp=''
                for letter in words[i]:
                    for data in zip(Letters, Morse):
                        if letter==data[0]:
                            temp+=data[1]
                words[i]=temp
            return len(set(words))
    
    class Solution(object):
        def uniqueMorseRepresentations(self, words):
            MORSE = [".-","-...","-.-.","-..",".","..-.","--.",
                     "....","..",".---","-.-",".-..","--","-.",
                     "---",".--.","--.-",".-.","...","-","..-",
                     "...-",".--","-..-","-.--","--.."]
    
            seen = {"".join(MORSE[ord(c) - ord('a')] for c in word)
                    for word in words}
    
            return len(seen)
    

    相关文章

      网友评论

          本文标题:[python] 2019-02-18

          本文链接:https://www.haomeiwen.com/subject/rrpzeqtx.html