Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to find the most common pair of characters in a string with Swift

1 Answer

0 votes
func findMostCommonPair(in s: String) -> (pair: String, count: Int)? {
    var pairFrequency: [String: Int] = [:]
    
    // Iterate through the string to get pairs of characters
    for i in 0..<(s.count - 1) {
        let startIndex = s.index(s.startIndex, offsetBy: i)
        let endIndex = s.index(startIndex, offsetBy: 1)
        let pair = String(s[startIndex...endIndex])
        
        // Update the frequency dictionary
        pairFrequency[pair, default: 0] += 1
    }
    
    // Find the most common pair
    if let (mostCommonPair, count) = pairFrequency.max(by: { $0.value < $1.value }) {
        return (mostCommonPair, count)
    }
    
    return nil
}

let s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";

if let result = findMostCommonPair(in: s) {
    print("Most common pair: \(result.pair) with count: \(result.count)")
} else {
    print("No pairs found.")
}




/*
run:

Most common pair: xz with count: 7

*/

 



answered Nov 28, 2024 by avibootz
...