3 回答

TA贡献2003条经验 获得超2个赞
虽然这看起来像是一个模式匹配任务,但由于字符串的长度非常有限,伪暴力检查可能是最简单的。
function pokerMatch(string $hand, string $pattern): bool
{
$hand = preg_replace('/[^a-z]/', '', $hand);
for ($i = 0; $i < strlen($hand); $i++) {
for ($j = $i+1; $j < strlen($hand); $j++) {
if ($pattern[$i] === $pattern[$j] && $hand[$i] !== $hand[$j]) {
return false;
}
if ($pattern[$i] !== $pattern[$j] && $hand[$i] === $hand[$j]) {
return false;
}
}
}
return true;
}
基本上这是做什么的,它遍历模式字符串,获取每对字符并检查:
如果模式位置 i 和 j 中的字母相等,则手串中的字符也必须相等;
如果模式位置 i 和 j 中的字母不同,则手串中的字符也必须不同;
如果其中任何一个不成立 - 模式不匹配
如果在检查所有对后我们没有发现不匹配 - 那么它是匹配的。
用法:
var_dump(pokerMatch('AsQdTc9h', 'xyzw')); // => bool(true)
var_dump(pokerMatch('AsQdTc9h', 'xyzz')); // => bool(false)
var_dump(pokerMatch('AsQsTc9c', 'xxyy')); // => bool(true)
var_dump(pokerMatch('AsQsTc9c', 'zzww')); // => bool(true) (it's agnostic to exact letters)

TA贡献1772条经验 获得超5个赞
$MyString = 'AsQdTc9h';
$MyString = preg_replace('/[^a-z]/', '', $MyString); // Get only the lowercase characters
// $MyString : sdch
$LetterArray = str_split($MyString);
$LetterArray = array_count_values($LetterArray);
$ReplaceList = ['x', 'y', 'z', 'w'];
$i = 0;
foreach ($LetterArray as $Letter => $result) {
$MyString = str_replace($Letter, $ReplaceList[$i], $MyString);
$i++;
}
echo $MyString; // expected output : xyzw
我想解释一下代码以便您理解它,首先我们使用正则表达式获取所有小写字符。然后我们将 4 个字符的单词转换为一个数组,然后我们计算有多少个字符是相同的。
然后我们将结果替换为 xyzw 。

TA贡献1863条经验 获得超2个赞
您可以通过遍历每手牌和搜索字符串来解决此问题,记录哪个花色与哪个搜索字母匹配,并检查它们是否始终一致:
$hands = ['AsQdTc9h', 'AsQsTd9d', 'AsKh9s9d'];
$searchStrings = ['xyxy', 'xyzw', 'yzyw', 'ppqq'];
function match_hand($hand, $search) {
$h = preg_replace('/[^a-z]/', '', $hand);
$matches = array();
for ($i = 0; $i < strlen($search); $i++) {
$s = $search[$i];
// have we seen this search letter before?
if (isset($matches[$s])) {
// does it match the previous value? if not, it's an error
if ($matches[$s] != $h[$i]) return false;
}
else {
// haven't seen this search letter before, so this hand letter should not be in the matches array yet
if (in_array($h[$i], $matches)) return false;
}
$matches[$s] = $h[$i];
}
return true;
}
foreach ($hands as $hand) {
foreach ($searchStrings as $search) {
if (match_hand($hand, $search)) {
echo "hand $hand matches pattern $search\n";
}
}
}
输出:
hand AsQdTc9h matches pattern xyzw
hand AsQsTd9d matches pattern ppqq
hand AsKh9s9d matches pattern yzyw
- 3 回答
- 0 关注
- 143 浏览
添加回答
举报