小屋創作

日誌2019-12-11 14:58

890. Find and Replace Pattern

作者:璃夕KaSyow₠

You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)
Return a list of the words in words that match the given pattern.
You may return the answer in any order.
class Solution {

    /**
     * @param String[] $words
     * @param String $pattern
     * @return String[]
     */

    function findAndReplacePattern($words, $pattern) {
        
        $res = array();
        $map1 =array();
        $map2 =array(); for($i=0;$i<count($words);$i++){
            $this->initmap($map1,$map2);
            $p = true ;
            for($s=0;$s<strlen($words[$i]);$s++){
                var_dump($map1[ord($pattern[$s])-97]);
                if($map1[ord($pattern[$s])-97] === 0 && $map2[ord($words[$i][$s])-97] === 0){
                    
                    $map1[ord($pattern[$s])-97] = $words[$i][$s];
                    $map2[ord($words[$i][$s])-97] = 1;
                }else if($map1[ord($pattern[$s])-97]!==$words[$i][$s]){
                    $p =false ;
                    break;
                }
        
            }
            if($p === true){
                array_push($res,$words[$i]);
            }
        }
        return $res ;
    }
    function initmap(&$m1,&$m2){
        if(isset($m1[0])){
            for($i=0;$i<26;$i++){
                $m1[$i] = $m2[$i] =0;
            }
        }else{
            for($i=0;$i<26;$i++){
                array_push($m1,0);
                array_push($m2,0);
            }
        }
    }
}

0

0

LINE 分享

相關創作

2

Project AJ Developer log.2

【方式】

留言

開啟 APP

face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】