Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if 2 strings contain the same characters?

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
like image 793
Brent Avatar asked Oct 21 '10 07:10

Brent


People also ask

How do you check if two strings have the same characters?

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 .

How do you find common characters in two strings?

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.

What method checks if two strings have the same text?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

How do I check if two strings have the same characters Python?

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.


Video Answer


1 Answers

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);
}
like image 167
GaryF Avatar answered Sep 21 '22 13:09

GaryF