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

别说谁变了你拦得住时间么 提交于 2019-12-31 02:14:09

问题


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?


回答1:


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)



回答2:


An elegant way could be :

extension String {
    func haveSameCharecterSet(_ str : String) -> Bool {
            return self.sorted() == str.sorted()
    }
}

May be used like this :

var str1 = "ABCD"
var str2 = "CDBA"
print(str1.haveSameCharecterSet(str2));
//true


来源:https://stackoverflow.com/questions/52329068/how-to-compare-two-strings-to-check-if-they-have-same-characters-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!