-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day 18; Queues and Stacks.swift
59 lines (46 loc) · 1.34 KB
/
Day 18; Queues and Stacks.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import Foundation
class Solution {
var pushedCharacters: [Character] = []
var enqueuedCharacters: [Character] = []
var popHead = 0
var enqueueHead = 0
func pushCharacter(ch: Character) {
self.pushedCharacters.append(ch)
}
func enqueueCharacter(ch: Character) {
self.enqueuedCharacters.append(ch)
}
func popCharacter() -> Character {
defer { popHead += 1 }
return self.pushedCharacters[pushedCharacters.endIndex - popHead - 1]
}
func dequeueCharacter() -> Character {
defer { enqueueHead += 1 }
return self.enqueuedCharacters[enqueueHead]
}
}
// read the string s.
let s = readLine()!
// create the Solution class object p.
let obj = Solution()
// push/enqueue all the characters of string s to stack.
for character in s {
obj.pushCharacter(ch: character)
obj.enqueueCharacter(ch: character)
}
var isPalindrome = true
// pop the top character from stack.
// dequeue the first character from queue.
// compare both the characters.
for _ in 0..<(s.count / 2) {
if obj.popCharacter() != obj.dequeueCharacter() {
isPalindrome = false
break
}
}
// finally print whether string s is palindrome or not.
if isPalindrome {
print("The word, \(s), is a palindrome.")
} else {
print("The word, \(s), is not a palindrome.")
}