Answer the question
In order to leave comments, you need to log in
How to find the most repeated character in a string?
I'm taking courses on swift, they asked DZ. In the material for dz there is not even a hint of solving this problem, and I don’t know where to look what to look for either. Please tell me how to solve this problem. Through a filter?
let frequents = "4878453556757364390942355"
Answer the question
In order to leave comments, you need to log in
A more visual solution, a dictionary is used, where the key is the character of the string, and the value is its number
let frequents = "1[3333ddflsd111kfl1111sdkfls1111dfZ"
var D = [Character: Int]()
for elem in frequents
{
if D.keys.contains(elem){
D[elem] = D[elem]!+1;
}
else
{
D[elem] = 1
}
}
var max = D.first
for elem in D{
if elem.value > max!.value
{
max = elem
}
}
print(max!)
"adflksdlfdfddddflsdkflsdkflsdfZ"
.lazy
.reduce(into: [Character:Int]()) { $0[$1] = $0[$1, default: 0] + 1 }
.sorted { $0.value < $1.value }
.last // (key: "d", value: 10)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question