코딩테스트 풀이/JAVA
[LeetCode/Easy] 884. Uncommon Words from Two Sentences
무지맘
2022. 12. 30. 01:23
1. Input
1) 문자열 s1
2) 문자열 s2
2. Output
1) s1과 s2에서 중복되지 않는 단어를 담은 문자열 배열
- 순서는 상관 없다.
3. Constraint
1) 1 <= s1.length, s2.length <= 200
2) s1과 s2는 영어 소문자와 공백 문자로 이루어져 있다.
3) 단어는 공백 문자 1개로 분리되어 있고, 불필요한 공백 문자는 존재하지 않는다.
4. Example
Input: s1 = "this apple is sweet", s2 = "this apple is sour" -> Output: ["sweet","sour"]
Input: s1 = "apple apple", s2 = "banana" -> Output: ["banana"]
5. Code
1) 첫 코드(2022/12/30)
import java.util.*;
HashMap<String,Integer> m = new HashMap<String,Integer>();
String[] words = s1.split(" ");
for(String w : words){
if(!m.containsKey(w)) m.put(w,1);
else m.replace(w, m.get(w)+1);
}
words = s2.split(" ");
for(String w : words){
if(!m.containsKey(w)) m.put(w,1);
else m.replace(w, m.get(w)+1);
}
ArrayList<String> list = new ArrayList<String>();
Set set = m.entrySet();
Iterator it = set.iterator();
while(it.hasNext()){
Map.Entry e = (Map.Entry)it.next();
if((int)e.getValue()==1) list.add((String)e.getKey());
}
return list.toArray(new String[] {});