leetcode Daily Challenge on January 22th, 2021.
Difficulty : Medium
Related Topics : Greedy
Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
- For example,
abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
- For example,
aacabb -> bbcbaa
(alla
's turn intob
's, and allb
's turn intoa
's)You can use the operations on either string as many times as necessary.
Given two strings,
word1
andword2
, returntrue
ifword1
andword2
are close, andfalse
otherwise.Input: word1 = "abc", word2 = "bca" Output: true Explanation: You can attain word2 from word1 in 2 operations. Apply Operation 1: "abc" -> "acb" Apply Operation 1: "acb" -> "bca"
Input: word1 = "a", word2 = "aa" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Input: word1 = "cabbba", word2 = "abbccc" Output: true Explanation: You can attain word2 from word1 in 3 operations. Apply Operation 1: "cabbba" -> "caabbb" Apply Operation 2: "caabbb" -> "baaccc" Apply Operation 2: "baaccc" -> "abbccc"
Input: word1 = "cabbba", word2 = "aabbss" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.
1 <= word1.length, word2.length <= 10^5
word1
andword2
contain only lowercase English letters.
- mine
- Java
Runtime: 12 ms, faster than 98.55%, Memory Usage: 40 MB, less than 50.54% of Java online submissions
public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] arr1 = new int[26]; int[] arr2 = new int[26]; for(char c : word1.toCharArray()){ arr1[c - 'a']++; } for(char c : word2.toCharArray()){ arr2[c - 'a']++; } int diffCount = 0; Map<Integer,Integer> map = new HashMap<>(); for(int i : arr1){ if(i != 0){ diffCount++; map.put(i, map.getOrDefault(i, 0) + 1); } } for(int i = 0; i < arr2.length; i++){ if(arr2[i] != 0){ if(arr1[i] == 0) return false; diffCount--; int v = map.getOrDefault(arr2[i], 0); if(v == 0) return false; else if(v == 1) map.remove(arr2[i]); else map.put(arr2[i], v - 1); } } return diffCount == 0 && map.size() == 0; }
- Java
- the most votes
Runtime: 14 ms, faster than 74.88%, Memory Usage: 39.7 MB, less than 66.88% of Java online submissions
public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] f1 = new int[26]; int[] v1 = new int[26]; for(char c : word1.toCharArray()) { f1[c - 'a']++; v1[c - 'a'] = 1; } int[] f2 = new int[26]; int[] v2 = new int[26]; for(char c : word2.toCharArray()) { f2[c - 'a']++; v2[c - 'a'] = 1; } Arrays.sort(f1); Arrays.sort(f2); return Arrays.equals(f1, f2) && Arrays.equals(v1, v2); }