単語パターン

Jan 01 2023
今日の Leetcode 問題 [ 2023 年 1 月 1 日 ]
パターンと文字列 s が与えられた場合、s が同じパターンに従うかどうかを調べます。ここで follow は、pattern 内の文字と s 内の空でない単語との間に全単射があるような完全一致を意味します。

apatternと stringを指定して、同じパターンに従うsかどうかを調べます。s

ここでfollowpatternは、 の文字との空でない単語の間に全単射があるような完全一致を意味しsます。

例 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

私たちが知っているように

「アバ」→「犬猫猫犬」

「あ」→「犬」

'b' -> 「猫」

異なる文字列を持つマップに遭遇した場合、それは有効なテスト ケースではないと言えます。

「アブファ」→「犬猫犬犬」

リートコード#290。単語パターン

「あ」→「犬」

'b' -> 「猫」

'f' -> 「犬」

しかし、犬はすでに a に割り当てられています。したがって、犬がすでに別のキャラクターにマッピングされていることがわかるように、1 つは a -> dog でマッピングを行い、もう 1 つのマップは dog -> a でマッピングを行います。

コードを始めましょう

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] tokens = s.split(" ");
        
        if(pattern.length() != tokens.length) 
            return false;

        HashMap<String, Character> map = new HashMap<>();
        HashMap<Character, String> reverseMap = new HashMap<>();

        for(int i=0;i<tokens.length;i++) {
            String find = tokens[i];
            char pt = pattern.charAt(i);
            
            if(!map.containsKey(find))
                map.put(find, pt);
            if(!reverseMap.containsKey(pt))
                reverseMap.put(pt, find);

            char mapPt = map.get(find);
            String mapStr = reverseMap.get(pt);
            
            if(mapPt != pt)
                return false;
            if(!mapStr.equals(find))
                return false;
        }
        return true;
    }
}