Checking if 2 strings contain the same characters?

Viewed 79652

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
13 Answers

This problem can be simply solved in O(n) time and O(1) space. The idea is to use a temp array of size 26 as we have only 26 characters in the alphabet.

First, if length of both strings are different we immediately return false. We iterate over length of the given string and in temp array, increase frequency of every character in string one and decrease count of character occured in other string. At the end temp array should have 0 count for every character if strings have equal characters.

Agree to what @Jean says above for an efficient solution using HashMap. This problem is also called Anagram. Below is the solution in Scala.

Note: cleanString is where whitespaces are removed and all characters are lowercase

def isAnagram(cleanString1, cleanString2) = {
  createHashMap(cleanString1) == createHashMap(cleanString2)
}

def createHashMap(str: String): immutable.HashMap[Char, Int] = {
  str.foldLeft(immutable.HashMap.empty[Char, Int]) { (acc, next)
  => if (acc.contains(next)) acc + (next -> (acc(next) + 1)) 
     else acc + (next -> 1)
     }
}
public static boolean isSameLetters(String word1, String word2){
    String s1 = Arrays.stream(word1.trim().strip().replaceAll("\\s","").split("")).sorted().collect(Collectors.joining());
    String s2 = Arrays.stream(word2.trim().strip().replaceAll("\\s","").split("")).sorted().collect(Collectors.joining());
    System.out.printf("word 1: %s\nword 2: %s\n",s1,s2);
    return s1.equals(s2);
}

//C++

#include<bits/stdc++.h>
using namespace std;

string cmpstr(string &s1,string &s2){

map<int,int>m1;
map<int,int>m2;

for(auto &c:s1)m1[c]++;
for(auto &c:s2)m2[c]++;

return m1==m2?"true":"false";


}
int main(){
    string s1,s2;
    cin>>s1>>s2;
    cout<<cmpstr(s1,s2);
    return 0;
}
public static void main(String[] a) {
        String s1 = "bore", s2 = "robe";
        char[] ch1 = s1.toCharArray();
        Arrays.sort(ch1);

        char[] ch2 = s2.toCharArray();
        Arrays.sort(ch2);
        System.out
                .println("Using array comparision method,Both strings contains same chars :" + Arrays.equals(ch1, ch2));

        String s11 = new String(ch1);
        String s22 = new String(ch2);
        System.out
                .println("Using String equals method,Both strings contains same chars : :" + s11.equalsIgnoreCase(s22));
    }

Here I have used Arrays & String class methods. Whatever comes at first in you mind you can use that. If comparison is the only purpose then use Arrays method and avoid creating string.

If you want o/p in string then anyway you will have to create strings.

Related