[刷题防痴呆] 0290 - 单词规律 (Word Patter

2021-12-18  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/word-pattern/description/

题目描述

290. Word Pattern

Given a pattern and a string str, find if str 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 str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.

思路

关键点

代码

class Solution {
    public boolean wordPattern(String pattern, String s) {

        Map<String, Character> wordMap = new HashMap<>();
        Map<Character, String> patternMap = new HashMap<>();
        String[] strs = s.split(" ");
        char[] sc = pattern.toCharArray();
        if (strs.length != sc.length) {
            return false;
        }

        for (int i = 0; i < strs.length; i++) {
            char c = sc[i];
            String word = strs[i];
            if (!wordMap.containsKey(word)) {
                wordMap.put(word, c);
            } else {
                if (!wordMap.get(word).equals(c)) {
                    return false;
                }
            }
            if (!patternMap.containsKey(c)) {
                patternMap.put(c, word);
            } else {
                if (!patternMap.get(c).equals(word)) {
                    return false;
                }
            }
        }

        return true;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读