【哈希】Leetcode 290. 单词规律【简单】

单词规律

  • 给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。(ps:就是字符和空格分隔出来的字符串映射)

示例1:

输入: pattern = “abba”, s = “dog cat cat dog”
输出: true

示例 2:

输入:pattern = “abba”, s = “dog cat cat fish”
输出: false

解题思路

  • 遍历字符串和规律,同时维护两个映射关系, 用于记录字符到字符串的映射和字符串到字符的映射。
  • 在遍历的过程中,检查当前字符与字符串的映射关系是否相符,若不相符则返回 false。

Java实现

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

        Map<Character, String> charToStr = new HashMap<>();
        Map<String, Character> strToChar = new HashMap<>();

        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            String word = words[i];

            //字符映射到字符串要一一对应
            if (!charToStr.containsKey(c)) {
                charToStr.put(c, word);
            } else {
                if (!charToStr.get(c).equals(word)) {
                    return false;
                }
            }

            //字符串映射到字符也要一一对应
            if (!strToChar.containsKey(word)) {
                strToChar.put(word, c);
            } else {
                if (strToChar.get(word) != c) {
                    return false;
                }
            }
        }

        return true;
    }

    public static void main(String[] args) {
        WordPattern wordPattern = new WordPattern();

        // Test Case 1
        String pattern1 = "abba";
        String s1 = "dog cat cat dog";
        System.out.println("Test Case 1:");
        System.out.println("pattern: \"" + pattern1 + "\", s: \"" + s1 + "\"");
        System.out.println("Result: " + wordPattern.wordPattern(pattern1, s1)); // Expected: true

        // Test Case 2
        String pattern2 = "abba";
        String s2 = "dog cat cat fish";
        System.out.println("\nTest Case 2:");
        System.out.println("pattern: \"" + pattern2 + "\", s: \"" + s2 + "\"");
        System.out.println("Result: " + wordPattern.wordPattern(pattern2, s2)); // Expected: false

    }
}

时间空间复杂度

  • 时间复杂度: 遍历规律和字符串,时间复杂度为 O(n),其中 n 是字符串的长度。
  • 空间复杂度:使用了两个HashMap来存储字符到字符串的映射和字符串到字符的映射,空间复杂度为O(n),其中n 是字符串的长度。
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值