3 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
雖然這看起來像是一個模式匹配任務(wù),但由于字符串的長度非常有限,偽暴力檢查可能是最簡單的。
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 中的字母不同,則手串中的字符也必須不同;
如果其中任何一個不成立 - 模式不匹配
如果在檢查所有對后我們沒有發(fā)現(xiàn)不匹配 - 那么它是匹配的。
用法:
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條經(jīng)驗 獲得超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 個字符的單詞轉(zhuǎn)換為一個數(shù)組,然后我們計算有多少個字符是相同的。
然后我們將結(jié)果替換為 xyzw 。

TA貢獻1863條經(jīng)驗 獲得超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 關(guān)注
- 131 瀏覽
添加回答
舉報