Swift solution with Dictionary


  • 0
    B
    func frequencySort(_ s: String) -> String {
            var table = [Character: Int]()
            for c in s.characters {
                if let count = table[c] {
                    table[c] = count + 1
                } else {
                    table[c] = 1
                }
            }
            // sort table
            let sortedTable = table.sorted { (first, second) -> Bool in
                return first.value > second.value
            }
            var string = ""
            for char in sortedTable {
                string += String(repeating: String(char.key), count: table[char.key]!)
            }
            return string
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.