【leetcode】888.Uncommon Words from Two Sentences解题报告

easy 题,求句子A与B在the other句子中没有出现的单词,前提是这个单词在本身句子中指出现了一次
方法一:
比较笨的方法,先把sentence A 和sentence B中的单词放到字典里,并记录其出现的次数,然后在依次遍历这两个字典,看字典中的单词是否在另一个sentence的字典中出现过

class Solution:
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        res = []
        dictA= {}
        dictB= {}
        A = A.split(" ")
        B = B.split(" ")
        for word in A:
            if word in dictA:
                dictA[word] +=1
            else:
                dictA[word] = 1

        for word in B:
            if word in dictB:
                dictB[word] +=1
            else:
                dictB[word] =1
        for word in dictA:
            if dictA[word]==1 and word not in dictB:
                res.append(word)
        for word in dictB:
            if dictB[word] ==1 and word not in dictA:
                res.append(word)
        return res

运行时间56ms

方法二:
把sentenceA 和sentenceB 的word放到同一个字典里,最后取计数器为1的单词即可
python

class Solution:
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        dictionary = {}
        res = []
        for word in A.split(" "):
            if word in dictionary:
                dictionary[word] +=1
            else:
                dictionary[word] =1
        for word in B.split(" "):
            if word in dictionary:
                dictionary[word] +=1
            else:
                dictionary[word] =1
        for word in dictionary:
            if dictionary[word] ==1:
                res.append(word)
        return res

运行时间 48ms

java

class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        List<String> reslist =  new ArrayList<String>();
        HashMap<String,Integer>  map =  new HashMap<String,Integer>();
        for(String word:A.split(" ")){
            if(map.containsKey(word)){
                map.put(word,map.get(word)+1);
            }
            else {
                map.put(word,1);
            }
        }
        for(String word:B.split(" ")){
            if(map.containsKey(word)){
                map.put(word,map.get(word)+1);
            }
            else {
                map.put(word,1);
            }
        }
        for(String key :map.keySet()){
            if (map.get(key)==1){
                reslist.add(key);
            }
            else
            continue;
        }
        String[] res = new String[reslist.size()];
        reslist.toArray(res);
        return res;

    }
}

猜你喜欢

转载自blog.csdn.net/dpengwang/article/details/81660196