-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclosed_bracket_word.php
More file actions
59 lines (55 loc) · 1.81 KB
/
closed_bracket_word.php
File metadata and controls
59 lines (55 loc) · 1.81 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
<?php
// 7 kyu - Simple Fun #215: Properly Closed Bracket Word
// We call letter x a counterpart of letter y, if x is the ith letter of the English alphabet, and y is the (27 - i)th for each valid i (1-based). For example, 'z' is the counterpart of 'a' and vice versa, 'y' is the counterpart of 'b', and so on.
//
// A properly closed bracket word (PCBW) is such a word that its first letter is the counterpart of its last letter, its second letter is the counterpart of its last by one letter, and so on.
//
// Determine if the given word is a PCBW or not.
//
// Input/Output
// [input] string word
//
// A string consisting of lowercase letters.
//
// 0 < word.length ≤ 30
//
// [output] a boolean value
//
// true if word is a PCBW, false otherwise.
//
// Example
// For word = "abiryz", the output should be true.
//
// 'a' is the counterpart of 'z';
//
// 'b' <-> 'y'
//
// 'i' <-> 'r'
//
// For word = "aibryz", the output should be false.
//
// For word = "abitryz", the output should be false.
function closed_bracket_word(string $word): bool {
for($i = 0; $i < strlen($word); $i++) {
if (ord(strtoupper($word[$i])) - 64 != 27 - (ord(strtoupper($word[strlen($word) -1 - $i])) - 64)) return false;
}
return true;
}
// Alternative solutions:
// function closed_bracket_word(string $w): bool {
// $a = "abcdefghijklmnopqrstuvwxyz";
// for ($i = 0; $i < strlen($w); $i++) {
// if (strpos($a, $w[$i]) != 25-strpos($a, $w[strlen($w)-$i-1])) { return false; }
// }
// return true;
// }
// function closed_bracket_word(string $word): bool {
// $al = str_split('abcdefghijklmnopqrstuvwxyz');
// $total = 1;
// $word = str_split($word);
// for($i = 0; $i < count($word)/2; $i++) {
// if($word[count($word) - ($i + 1)] != $al[25 - array_search($word[$i], $al)]) $total = false;
// }
// return $total;
// }
?>