S
S
Sir0zha2019-10-22 17:44:09
iOS
Sir0zha, 2019-10-22 17:44:09

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

2 answer(s)
V
Viktor Paperno, 2019-10-22
@Sir0zha

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

D
doublench21, 2019-10-22
@doublench21

5daf297d86524526184825.png

text
"adflksdlfdfddddflsdkflsdkflsdfZ"
  .lazy
  .reduce(into: [Character:Int]()) { $0[$1] = $0[$1, default: 0] + 1 }
  .sorted { $0.value < $1.value }
  .last // (key: "d", value: 10)

Z.Y. Works extremely fast.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question