Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e9ed525

Browse files
committed
953:Add solution for Verifying an Alien Dictionary problem
1 parent a28a58e commit e9ed525

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
class Solution
3+
{
4+
/**
5+
* @param String[] $words
6+
* @param String $order
7+
* @return Boolean
8+
*/
9+
public function isAlienSorted($words, $order)
10+
{
11+
$orderMap = [];
12+
for ($i = 0; $i < strlen($order); $i++) {
13+
$orderMap[$order[$i]] = $i;
14+
}
15+
16+
for ($i = 0; $i < count($words) - 1; $i++) {
17+
if (! self::isInOrder($words[$i], $words[$i + 1], $orderMap)) {
18+
return false;
19+
}
20+
}
21+
return true;
22+
}
23+
24+
private static function isInOrder($word1, $word2, $orderMap)
25+
{
26+
$len1 = strlen($word1);
27+
$len2 = strlen($word2);
28+
$minLen = min($len1, $len2);
29+
30+
for ($i = 0; $i < $minLen; $i++) {
31+
if ($orderMap[$word1[$i]] < $orderMap[$word2[$i]]) {
32+
return true;
33+
} elseif ($orderMap[$word1[$i]] > $orderMap[$word2[$i]]) {
34+
return false;
35+
}
36+
}
37+
return $len1 <= $len2;
38+
}
39+
}
40+
41+
$solution = new Solution();
42+
$words = ["hello", "leetcode"];
43+
$order = "hlabcdefgijkmnopqrstuvwxyz";
44+
echo $solution->isAlienSorted($words, $order) ? "true" : "false"; // Output: true

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /