Search code examples
swiftlogicswift4

How to compare two Strings to check if they have same Characters Swift 4?


I was playing around on HackerEarth and I came across this issue.

What I try to do is to compare the strings and check if they have the same characters or not.

var string = ""

while let thing = readLine() 
{ 
string += thing + " "
}

var arrayStr = string.split(separator: " ").map{String(($0))}

var firstString = [String]()

var secondString = [String]()

var cas = arrayStr[0]

for i in 1..<arrayStr.count
{
if i % 2 != 0 
{
    firstString.append(String(arrayStr[i]))
}
else
{
    secondString.append(String(arrayStr[i]))
}
}
print(firstString) //["sumit", "ambuj", "abhi"]


print(secondString) //["mitsu", "jumba", "hibb"]

So, now you can see that the first index of firstString and secondString contains the same character, same for the second index, but not for the last one.

So, how can I compare them? I tried NSCharacter, but HackerEarth is not picking that up. Any ideas?


Solution

  • If “multiplicity” counts (i.e. "aab" has the same characters as "aba", but not the same characters as "abb"), then

    s1.sorted() == s2.sorted()
    

    does the trick. If you don't care about the multiplicity, then just

    Set(s1) == Set(s2)
    

    Example:

    let firstArray = ["sumit", "ambuj", "abhi", "aba"]
    let secondArray = ["mitsu", "jumba", "hibb", "abb"]
    
    for (s1, s2) in zip(firstArray, secondArray) {
        print(s1.sorted() == s2.sorted())
    }
    
    // true, true, false, false
    
    for (s1, s2) in zip(firstArray, secondArray) {
        print(Set(s1) == Set(s2))
    }
    
    // true, true, false, true
    

    For longer strings it might be more efficient to maintain a dictionary with the number of occurrences of each character in a string (similar to a NSCountedSet):

    func characterCounts(_ s: String) -> [Character: Int] {
        return s.reduce(into: [:], { $0[$1, default: 0] += 1 })
    }
    

    and then compare the dictionaries:

    characterCounts(s1) == characterCounts(s2)