Determine if Two Strings Are Close - LeetCode
Runtime : 7ms And Beats : 99.8%
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length() != word2.length()) return false;
if (word1.equals(word2)) return true;
byte[] ch1 = word1.getBytes() , ch2 = word2.getBytes();
int [] arr1 = new int[26] , arr2 = new int[26];
for (byte c : ch1){
arr1[c - 'a']++;
}
for (byte c : ch2)
{
if (arr1[c - 'a'] == 0) return false;
arr2[c - 'a']++;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
int i = 25;
while (arr1[i] != 0 && i > 0 )
{
if (arr1[i] != arr2[i]) return false;
i--;
}
return true;
}
}
Runtime : 32ms And Beats : 54**%**
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length() != word2.length()) return false;
HashSet<Character> hashSet = new HashSet<>();
char[] ch1 = word1.toCharArray() , ch2 = word2.toCharArray();
int [] arr1 = new int[26] , arr2 = new int[26];
for (char c : ch1)
{
hashSet.add(c);
arr1[c - 'a']++;
}
for (char c : ch2)
{
if (!hashSet.contains(c)) return false;
arr2[c - 'a']++;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1 , arr2);
}
}
Runtime : 86ms And Beats : 20**%**
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length() != word2.length()) return false;
char[] ch1 = word1.toCharArray() , ch2 = word2.toCharArray();
ConcurrentHashMap<Character , Integer> hashMap1 = new ConcurrentHashMap<>();
ConcurrentHashMap<Character , Integer> hashMap2 = new ConcurrentHashMap<>();
for (int i = 0; i < ch1.length ; i++)
{
//or hashMap1.merge(ch1[i], 1, Integer::sum);
hashMap1.put(ch1[i] , hashMap1.getOrDefault(ch1[i] , 0) + 1) ;
hashMap2.put(ch2[i] , hashMap2.getOrDefault(ch2[i] , 0) + 1) ;
}
if (hashMap1.size() != hashMap2.size()) return false;
int [] arr1 = new int[hashMap1.size()] , arr2 = new int[hashMap1.size()];
int i = 0;
for (Map.Entry<Character , Integer> map : hashMap1.entrySet())
{
arr1[i] = map.getValue();
if (!hashMap2.containsKey(map.getKey())) return false;
arr2[i] = hashMap2.get(map.getKey());
i++;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1 , arr2);
}
}