-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordPattern.php
More file actions
61 lines (52 loc) · 1.41 KB
/
Copy pathWordPattern.php
File metadata and controls
61 lines (52 loc) · 1.41 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
<?php
namespace App;
/**
* Word Pattern
*
* Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there
* is a bijection between a letter in pattern and a non-empty word in s.
*
* Example 1:
* Input: pattern = "abba", s = "dog cat cat dog"
* Output: true
*
* Example 2:
* Input: pattern = "abba", s = "dog cat cat fish"
* Output: false
*
* Example 3:
* Input: pattern = "aaaa", s = "dog cat cat dog"
* Output: false
*
* https://leetcode.com/problems/word-pattern
*/
class WordPattern
{
/**
* @param string $pattern
* @param string $str
* @return bool
*/
public function wordPattern(string $pattern, string $str): bool
{
$words = explode(' ', $str);
$patternChars = str_split($pattern);
if (count($words) !== count($patternChars)) {
return false;
}
$patternMap = [];
$wordMap = [];
foreach ($patternChars as $index => $patternChar) {
$word = $words[$index];
if (isset($patternMap[$patternChar]) && $patternMap[$patternChar] !== $word) {
return false;
}
if (isset($wordMap[$word]) && $wordMap[$word] !== $patternChar) {
return false;
}
$patternMap[$patternChar] = $word;
$wordMap[$word] = $patternChar;
}
return true;
}
}