/
day18.php
84 lines (67 loc) · 1.61 KB
/
day18.php
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
class Solution {
public $stack;
public $top;
public $queue;
public $front;
public function __construct()
{
$this->stack = array();
$this->top = -1;
$this->queue = array();
$this->front = 0;
$this->back = -1;
}
public function pushCharacter($s)
{
$this->top++;
$this->stack[$this->top] = $s;
}
public function enqueueCharacter($s)
{
$this->back++;
$this->queue[$this->back] = $s;
}
public function popCharacter()
{
if ($this->top === -1) return null;
$last = $this->stack[$this->top];
$this->top--;
return $last;
}
public function dequeueCharacter()
{
if ($this->back === -1) return null;
$first = $this->queue[$this->front];
$this->front++;
return $first;
}
}
// read the string s
$s = fgets(STDIN);
// create the Solution class object p
$obj = new Solution();
$len = strlen($s);
$isPalindrome = true;
// push/enqueue all the characters of string s to stack
for ($i = 0; $i < $len; $i++) {
$obj->pushCharacter($s{$i});
$obj->enqueueCharacter($s{$i});
}
/*
pop the top character from stack
dequeue the first character from queue
compare both the characters
*/
for ($i = 0; $i < $len / 2; $i++) {
if($obj->popCharacter() != $obj->dequeueCharacter()){
$isPalindrome = false;
break;
}
}
//finally print whether string s is palindrome or not.
if ($isPalindrome)
echo "The word, ".$s.", is a palindrome.";
else
echo "The word, ".$s.", is not a palindrome.";
?>