C#LeetCode刷题之#884-两句话中的不常见单词(Uncommon Words from Two Sentences)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3816 访问。

给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。

返回所有不常用单词的列表。

您可以按任何顺序返回列表。

输入:A = "this apple is sweet", B = "this apple is sour"

输出:["sweet","sour"]

输入:A = "apple apple", B = "banana"

输出:["banana"]

提示:

0 <= A.length <= 200
0 <= B.length <= 200
A 和 B 都只包含空格和小写字母。


We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words. 

You may return the list in any order.

Input: A = "this apple is sweet", B = "this apple is sour"

Output: ["sweet","sour"]

Input: A = "apple apple", B = "banana"

Output: ["banana"]

Note:

0 <= A.length <= 200
0 <= B.length <= 200
A and B both contain only spaces and lowercase letters.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3816 访问。

public class Program {

    public static void Main(string[] args) {
        var A = "this apple is sweet";
        var B = "this apple is sour";

        var res = UncommonFromSentences(A, B);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(IList array) {
        foreach(var domain in array) {
            Console.Write($"{domain} ");
        }
        Console.WriteLine();
    }

    private static string[] UncommonFromSentences(string A, string B) {
        string[] wordA = A.Split(' ');
        string[] wordB = B.Split(' ');
        var dicA = new Dictionary();
        var dicB = new Dictionary();
        var res = new List();
        foreach(var word in wordA) {
            if(dicA.ContainsKey(word)) {
                dicA[word]++;
            } else {
                dicA[word] = 1;
            }
        }
        foreach(var word in wordB) {
            if(dicB.ContainsKey(word)) {
                dicB[word]++;
            } else {
                dicB[word] = 1;
            }
        }
        foreach(var kvp in dicA) {
            if(kvp.Value == 1 && !dicB.ContainsKey(kvp.Key)) {
                res.Add(kvp.Key);
            }
        }
        foreach(var kvp in dicB) {
            if(kvp.Value == 1 && !dicA.ContainsKey(kvp.Key)) {
                res.Add(kvp.Key);
            }
        }
        return res.ToArray();
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3816 访问。

sweet sour

分析:

显而易见,以上算法的时间复杂度为: O(n)

你可能感兴趣的:(C#LeetCode刷题,C#LeetCode)