【LeetCode】290. Word Pattern 单词规律(Easy)(JAVA)每日一题

【LeetCode】290. Word Pattern 单词规律(Easy)(JAVA)

题目地址: https://leetcode.com/problems/word-pattern/

题目描述:

Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

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

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ’ '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

题目大意

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

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律

说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。

解题方法

  1. 要字符和字符串一一对应,不能是多对一也不能是一对多
  2. 把对应关系记录下来,然后每次查看是否相同即可
  3. note: 要考虑长度不一的问题
class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> map = new HashMap<>();
        Set<String> set = new HashSet<>();
        int index = 0;
        for (int i = 0; i < pattern.length(); i++) {
            char ch = pattern.charAt(i);
            int start = index;
            if (index >= s.length()) return false;
            while (index < s.length() && s.charAt(index) != ' ') {
                index++;
            }
            String cur = s.substring(start, index);
            index++;
            String pre = map.get(ch);
            if (pre == null) {
                if (set.contains(cur)) return false;
                set.add(cur);
                map.put(ch, cur);
            } else {
                if (!pre.equals(cur)) return false;
            }
        }
        return index >= s.length();
    }
}

执行耗时:1 ms,击败了98.94% 的Java用户
内存消耗:36.4 MB,击败了80.89% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值