Skip to content

Instantly share code, notes, and snippets.

@alimir1
Last active August 2, 2023 19:06
Show Gist options
  • Save alimir1/83b94be5fde4ef8b51ba6bf6044e78cd to your computer and use it in GitHub Desktop.
Save alimir1/83b94be5fde4ef8b51ba6bf6044e78cd to your computer and use it in GitHub Desktop.
Check if string is palindrome Swift 3
func isPalindrome(_ word: String) -> Bool {
let word = word.lowercased().characters.filter{ $0 != " " }
for (i, character) in word.enumerated() {
if character != word[word.count-i-1] {
return false
}
}
return true
}
@Kastet
Copy link

Kastet commented Jan 10, 2018

func isPalindrome(word: String) -> Bool {
    let word = word.lowercased().filter { $0 != " " }
    return word == String(word.reversed())
}
  

@bolaibrahim1
Copy link

func checkPalindrome(_ inputString: String) -> Bool { if inputString.count % 2 == 0 { return false } else if inputString.count == 1 { return true } else { var stringCount = inputString.count while stringCount != 1 { if inputString.first == inputString.last { stringCount -= 2 } else { continue } } if stringCount == 1 { return true } else { return false } } }

@sohaeb
Copy link

sohaeb commented Apr 3, 2019

Swift 5 of alimir solution top:


func isPalindrome(_ word: String) -> Bool {
    let word = word.filter { $0 != " " }
    for (i, character) in word.enumerated() {
        if character != Array(word)[word.count-i-1] {
            return false
        }
    }
    return true
}

@israman30
Copy link

israman30 commented Jul 24, 2019

func palindrome(string: String)-> Bool{
    let char = Array(string)
    for i in 0..<char.count / 2 {
        if char[i] != char[char.count - 1 - i] {
            return false
        }
    }
    return true
}

@NateFuller
Copy link

NateFuller commented May 18, 2022

While loop implementation:

extension StringProtocol {
  subscript(_ offset: Int) -> Element { self[index(startIndex, offsetBy: offset)] }
}

func isPalindrome(_ input: String) -> Bool {
  guard input.count > 1 else { return true }
  var lhs = 0; var rhs = input.count - 1

  while lhs < rhs {
    guard input[lhs] == input[rhs] else { return false }

    lhs += 1; rhs -= 1
  }

  return true
}

@Gurwindersingh1992
Copy link

Anybody suggest how can achieve using high order func i.e Map or any ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment