Skip to content

Instantly share code, notes, and snippets.

@thepost
Last active May 24, 2018 19:13
Show Gist options
  • Save thepost/d6cc8bd6bcd4c3c47abed3b3791011d0 to your computer and use it in GitHub Desktop.
Save thepost/d6cc8bd6bcd4c3c47abed3b3791011d0 to your computer and use it in GitHub Desktop.
Finding a palindrome using a queue and a stack in Swift
public struct Stack<Element>
{
fileprivate var stackItems: [Element] = [Element]()
public init() {}
public mutating func pop() -> Element? {
guard !stackItems.isEmpty else {
return nil
}
return stackItems.removeLast()
}
public mutating func push(item:Element) {
stackItems.append(item)
}
public func isEmpty() -> Bool {
return stackItems.isEmpty
}
}
public class Queue<Element: Equatable>
{
fileprivate var stackIn: Stack = Stack<Element>()
fileprivate var stackOut: Stack = Stack<Element>()
func enqueue(item:Element) {
stackIn.push(item: item)
}
func dequeue() -> Element? {
if stackOut.isEmpty() {
//Shift stackIn data into stackOut...
while !stackIn.isEmpty() {
if let toShift = stackIn.pop() {
stackOut.push(item: toShift)
}
}
}
return stackOut.pop()
}
}
public struct PalindromeSolution {
//Write your code here
var stack: Stack = Stack<Character>()
var queue: Queue = Queue<Character>()
public init() {}
public func pushCharacter(ch: Character) {
//Pushes the char onto the `stack`
stack.push(item:ch)
}
public func enqueueCharacter(ch: Character) {
//Enqueues the char onto the `queue`
queue.enqueue(item:ch)
}
public func popCharacter() -> Character {
//Pops and returns the char at the top of the `stack`
let popped: Character = stack.pop()! as Character
return popped
}
public func dequeueCharacter() -> Character {
//Dequeues and returns the char at end of the `queue`
let dequeued: Character = queue.dequeue()! as Character
return dequeued
}
}
public struct PalindromeFinder {
let stackQueue: PalindromeSolution = PalindromeSolution()
public func findPalindrome(inString str: String) -> Bool {
for char in str {
stackQueue.pushCharacter(ch: char)
stackQueue.enqueueCharacter(ch: char)
}
var isPalindrome = true
for _ in 0..<(str.count / 2) {
if stackQueue.popCharacter() != stackQueue.dequeueCharacter() {
isPalindrome = false
break
}
}
return isPalindrome
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment