Is there a way to check if two strings contain the same characters. For example,
abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def -> false
Turn each string into a char[], sort that array, then compare the two. No, if we were removing duplicates then "aab, bba" would return true and it's specified as returning false. Arrays. equals , not equal .
Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
String Comparison using == in PythonThe == function compares the values of two strings and returns if they are equal or not. If the strings are equal, it returns True, otherwise it returns False.
Turn each string into a char[], sort that array, then compare the two.
private boolean sameChars(String firstStr, String secondStr) {
char[] first = firstStr.toCharArray();
char[] second = secondStr.toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With