如何比较两个字符串以检查它们是否具有相同的字符Swift 4? [英] How to compare two Strings to check if they have same Characters Swift 4?

查看:720
本文介绍了如何比较两个字符串以检查它们是否具有相同的字符Swift 4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HackerEarth上玩耍,遇到了这个问题.

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"]

因此,现在您可以看到firstStringsecondString的第一个索引包含相同的字符,第二个索引相同,而最后一个索引则不包含.

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.

那么,我该如何比较它们呢?我尝试了NSCharacter,但是HackerEarth并没有做到这一点.有什么想法吗?

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

推荐答案

如果多重性"很重要(即"aab"与"aba"具有相同的字符, 但与"abb"字符不同),然后

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)

示例:

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

对于更长的字符串,维护字符串可能会更有效 dictionary ,其中每个字符出现的次数 字符串(类似于NSCountedSet):

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 })
}

然后比较字典:

characterCounts(s1) == characterCounts(s2)

这篇关于如何比较两个字符串以检查它们是否具有相同的字符Swift 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆