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?
An elegant way could be :
May be used like this :
If “multiplicity” counts (i.e. "aab" has the same characters as "aba", but not the same characters as "abb"), then
does the trick. If you don't care about the multiplicity, then just
Example:
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
):and then compare the dictionaries: