|
| 1 | +/** |
| 2 | +* We are given two sentences A and B. (A sentence is a string of space separated |
| 3 | +* words. Each word consists only of lowercase letters.) |
| 4 | +* |
| 5 | +* A word is uncommon if it appears exactly once in one of the sentences, and |
| 6 | +* does not appear in the other sentence. |
| 7 | +* |
| 8 | +* Return a list of all uncommon words. |
| 9 | +* |
| 10 | +* You may return the list in any order. |
| 11 | +* |
| 12 | +* Example 1: |
| 13 | +* Input: A = "this apple is sweet", B = "this apple is sour" |
| 14 | +* Output: ["sweet","sour"] |
| 15 | +* |
| 16 | +* Example 2: |
| 17 | +* Input: A = "apple apple", B = "banana" |
| 18 | +* Output: ["banana"] |
| 19 | +* |
| 20 | +* Note: |
| 21 | +* 0 <= A.length <= 200 |
| 22 | +* 0 <= B.length <= 200 |
| 23 | +* A and B both contain only spaces and lowercase letters. |
| 24 | +*/ |
| 25 | + |
| 26 | +public class UncommonWordsFromTwoSentences884 { |
| 27 | +public String[] uncommonFromSentences(String A, String B) { |
| 28 | +Set<String> once = new HashSet<>(); |
| 29 | +Set<String> mult = new HashSet<>(); |
| 30 | +String[] as = A.split(" "); |
| 31 | +for (String s: as) { |
| 32 | +if (once.contains(s)) { |
| 33 | +once.remove(s); |
| 34 | +mult.add(s); |
| 35 | +} else if (!mult.contains(s)) { |
| 36 | +once.add(s); |
| 37 | +} |
| 38 | +} |
| 39 | + |
| 40 | +String[] bs = B.split(" "); |
| 41 | +Set<String> resCand = new HashSet<>(); |
| 42 | +Set<String> resMult = new HashSet<>(); |
| 43 | +for (String s: bs) { |
| 44 | +if (!once.contains(s) && !mult.contains(s)) { |
| 45 | +if (resCand.contains(s)) { |
| 46 | +resCand.remove(s); |
| 47 | +resMult.add(s); |
| 48 | +} else if (!resMult.contains(s)) { |
| 49 | +resCand.add(s); |
| 50 | +} |
| 51 | +} else if (once.contains(s)) { |
| 52 | +once.remove(s); |
| 53 | +mult.add(s); |
| 54 | +} |
| 55 | +} |
| 56 | + |
| 57 | +String[] res = new String[resCand.size() + once.size()]; |
| 58 | +int i = 0; |
| 59 | +for (String c: resCand) { |
| 60 | +res[i++] = c; |
| 61 | +} |
| 62 | +for (String c: once) { |
| 63 | +res[i++] = c; |
| 64 | +} |
| 65 | +return res; |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | +* https://leetcode.com/problems/uncommon-words-from-two-sentences/solution/ |
| 70 | +*/ |
| 71 | +public String[] uncommonFromSentences2(String A, String B) { |
| 72 | +Map<String, Integer> count = new HashMap(); |
| 73 | +for (String word: A.split(" ")) |
| 74 | +count.put(word, count.getOrDefault(word, 0) + 1); |
| 75 | +for (String word: B.split(" ")) |
| 76 | +count.put(word, count.getOrDefault(word, 0) + 1); |
| 77 | + |
| 78 | +List<String> ans = new LinkedList(); |
| 79 | +for (String word: count.keySet()) |
| 80 | +if (count.get(word) == 1) |
| 81 | +ans.add(word); |
| 82 | + |
| 83 | +return ans.toArray(new String[ans.size()]); |
| 84 | +} |
| 85 | +} |
0 commit comments