Algorithms: Special Palindrome in Swift

Subscribe to my newsletter and never miss my upcoming articles

Hey everybody, Leo here.

Today we'll continue the series Algorithms, the Final Frontier. Always remember, this is ONE of many possible solution for the problem.

Let's go!

Given a string, find the longest substring which is palindrome and return his it length. The two words must have the same ending letter. Ex: "LeoeL" should return 5 but "LeooeL" should return 0.

So here the solution a came was to manipulate 2 pointer inside a string. Check the solution above and you can copy/paste into your playgrounds to play around.

//test data
let return7 = "rooooor" // return 7
let return5 = "leoel" // should return 5
let return3 = "adfwefvcsadrooo" //should return 3
let return3again = "oooadfwefvcsadroooo" // should return 3
let return4 = "oooadfwefvcsadrooooo" //should return 5


func palindrome(_ word: String) -> Int {

    if word.count < 3 {
        return 0
    }

    var tempResult = 0
    var maxResult = 0
    let array = Array(word)
    let arrayCount = array.count

    for x in 1..<arrayCount-1 {
        for y in 1...arrayCount {
            if !(x-y < 0) && !(x+y > arrayCount-1) {
                if array[x-y] == array[x+y] {
                    if tempResult == 0 {
                        tempResult += 3
                    } else {
                        tempResult += 2
                    }
                } else {
                    break
                }
            } else {
                break
            }
        }
        if tempResult > maxResult {
            maxResult = tempResult
        }
        tempResult = 0
    }
    return maxResult
}
//testing
palindrome(return5)
palindrome(return7)
palindrome(return3)
palindrome(return3again)
palindrome(return4)

Trivia time!

History of the Palindrome The word palindrome is derived from the Greek 'palin,' or "back" and 'dromos' or "direction." The actual Greek phrase alluded to the backward movement of the crab. Palindromes date back to about 70AD, when they were first found as a graffito buried in ash at Herculaneum.

Thanks for the reading and... That's all folks!

No Comments Yet