46.单词规律-LeetCode-Java

2022-08-03,,,,

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true

示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false

示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false

示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母
import java.util.HashMap;
class Solution {
    public boolean wordPattern(String pattern, String str) {

        HashMap map = new HashMap();
        String[] word = str.split(" ");

        if (pattern.length() != word.length) return false;

        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (!map.containsKey(c)) {
                if (map.containsValue(word[i])) return false;
                map.put(c, word[i]);
            } else {
                if (!map.get(c).equals(word[i])) return false;
            }
        }
        return true;
    }
}

本文地址:https://blog.csdn.net/weixin_44171910/article/details/107351660

《46.单词规律-LeetCode-Java.doc》

下载本文的Word格式文档,以方便收藏与打印。