-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome.php
More file actions
100 lines (80 loc) · 2.34 KB
/
Palindrome.php
File metadata and controls
100 lines (80 loc) · 2.34 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
namespace Ianriizky\CodingInterview\Palindrome;
class Palindrome
{
/**
* Create a new instance class.
*
* @return void
*/
public function __construct(
protected string $value
) {
$this->value = $this->sanitize($value);
}
/**
* Create a new instance class in a static way.
*
* @return static
*/
public static function make(string $value)
{
return new static($value);
}
/**
* Determine whether the given value is a palindrome or not using reverse way.
*/
public function checkUsingReverse(): bool
{
$value = $this->value;
$newValue = '';
for ($index = strlen($value) - 1; $index >= 0; $index--) {
$newValue .= $value[$index];
}
return $value === $newValue;
}
/**
* Determine whether the given value is a palindrome or not using loop way.
*/
public function checkUsingLoop(): bool
{
$value = $this->value;
for ($index = 0; $index < floor(strlen($value) / 2); $index++) {
$lastCharacterIndex = strlen($value) - ($index + 1);
$firstCharacter = $value[$index];
$lastCharacter = $value[$lastCharacterIndex];
if ($firstCharacter !== $lastCharacter) {
return false;
}
}
return true;
}
/**
* Determine whether the given value is a palindrome or not using recursive way.
*/
public function checkUsingRecursive(int $index = 0): bool
{
$value = $this->value;
if ($index < floor(strlen($value) / 2)) {
$lastCharacterIndex = strlen($value) - ($index + 1);
$firstCharacter = $value[$index];
$lastCharacter = $value[$lastCharacterIndex];
if ($firstCharacter !== $lastCharacter) {
return false;
}
return $this->checkUsingRecursive($index + 1);
}
return true;
}
/**
* Sanitize the given value by running some specific task.
*/
protected function sanitize(string $value): string
{
$value = str_replace(' ', '', $value);
$value = str_replace('-', '', $value);
$value = preg_replace('/[^A-Za-z0-9\-]/', '', $value);
$value = mb_strtolower($value, 'UTF-8');
return $value;
}
}