Given an array strings, determine whether it follows the sequence given in the patterns array. In other words, there should be no i and j for which strings[i] = strings[j] and patterns[i] ≠ patterns[j] or for which strings[i] ≠ strings[j] and patterns[i] = patterns[j].
Example
strings = ["cat", "dog", "dog"] and patterns = ["a", "b", "b"], the output should be**solution(strings, patterns) = true**;strings = ["cat", "dog", "doggy"] and patterns = ["a", "b", "b"], the output should be**solution(strings, patterns) = false**.Input/Output
[execution time limit] 3 seconds (java)
[memory limit] 1 GB
[input] array.string strings
An array of strings, each containing only lowercase English letters.
Guaranteed constraints:
1 ≤ strings.length ≤ 105,
1 ≤ strings[i].length ≤ 10.
[input] array.string patterns
An array of pattern strings, each containing only lowercase English letters.
Guaranteed constraints:
patterns.length = strings.length,
1 ≤ patterns[i].length ≤ 10.
[output] boolean
Return true if strings follows patterns and false otherwise.
boolean solution(String[] strings, String[] patterns) {
// 패턴 = 문자열 의 HashMap 자료구조로 저장
LinkedHashMap <String, String> map = new LinkedHashMap<>();
for (int i = 0; i < strings.length; i ++) {
// 패턴 = key
String pattern = patterns[i];
// 문자열 = value
String str = strings[i];
// 해당 패턴의 키가 있을 때
if (map.containsKey(pattern)) {
// 해당 키의 값이 현재 문자열과 다르다면 거짓
if (!map.get(pattern).equals(str)) return false;
}
// 해당 패턴의 키가 없을 때
else {
// 자료구조에 해당 문자열이 값으로 존재하면 거짓
if (map.containsValue(str)) return false;
map.put(pattern, str);
}
}
return true;
}