Open songyy5517 opened 6 months ago
Approach: HashMap & Comparison of keySet & values
hm1.keySet().equals(hm2.keySet())
;values -> array -> sort -> Arrays.euqals
.Complexity Analysis
import java.util.*;
class Solution {
public boolean closeStrings(String word1, String word2) {
// Intuition: HashMap, comparision of keySet & values.
// 1. Exception handling
if (word1 == null || word2 == null || word1.length() != word2.length())
return false;
// 2. Define HashMap
HashMap<Character, Integer> hm1 = new HashMap();
HashMap<Character, Integer> hm2 = new HashMap();
for (int i = 0; i < word1.length(); i++){
hm1.put(word1.charAt(i), hm1.getOrDefault(word1.charAt(i), 0) + 1);
hm2.put(word2.charAt(i), hm2.getOrDefault(word2.charAt(i), 0) + 1);
}
// 3. Compare keySet and values of two HashMap
// values -> Interger[] -> Sort -> Arrays.equal
Object[] hm1_ = hm1.values().toArray();
Integer[] hm2_ = hm2.values().toArray(new Integer[hm2.size()]);
Arrays.sort(hm1_);
Arrays.sort(hm2_);
return hm1.keySet().equals(hm2.keySet()) && Arrays.equals(hm1_, hm2_);
}
}
2024/5/17
hm1.keySet().equals(hm2.keySet());
hm.values().toArray(); hm.values().toArray(new Integer[hm.size()]);
Two strings are considered close if you can attain one from the other using the following operations:
You can use the operations on either string as many times as necessary. Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Example 1:
Example 2:
Example 3:
Intuition The problem is to determine whether two strings are close. From the description, we know there are two conditions to determine whether two strings are close. For the first one, we can infer that close strings are those which have the same character set and the same occurence of each character. For the other case, close strings must have the same character set and occurence set, but the mapping between the character set and the ocurrence set can be different. Therefore, we can use two hashmaps to record the characters and their corresponding ocurrences in each string. If the key set and the value set of two hashmaps contain same elements, then the two strings are close; vice versa.