[LeetCode] 290. 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

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase 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 和一个字符串 s ,判断 s 是否遵循相同的规律。

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/word-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题的做法不难想,需要用 hashmap 记录 pattern 里面每个字母跟 str 里面每个单词的对应关系。注意如果出现一个字母对应的单词跟 hashmap 里记录的不一致,则返回 false;同时,如果出现一个已经被 hashmap 记录过的单词居然跟别的字母匹配,那样也是错的。这个地方跟205题一样,pattern 里面每个字母跟 str 里面每个单词的对应关系是单向的。

时间O(n^2) - 因为 hashmap 在判断 containsValue() 的时候,是 O(n) 级别的

空间O(n)

Java实现

 1 class Solution {
 2     public boolean wordPattern(String pattern, String s) {
 3         // corner case
 4         String[] array = s.split(" ");
 5         if (pattern.length() != array.length) {
 6             return false;
 7         }
 8 
 9         // normal case
10         HashMap<Character, String> map = new HashMap<>();
11         for (int i = 0; i < pattern.length(); i++) {
12             char cur = pattern.charAt(i);
13             if (map.containsKey(cur)) {
14                 if (map.get(cur).equals(array[i])) {
15                     continue;
16                 } else {
17                     return false;
18                 }
19             } else {
20                 if (!map.containsValue(array[i])) {
21                     map.put(cur, array[i]);
22                 } else {
23                     return false;
24                 }
25             }
26         }
27         return true;
28     }
29 }

 

相关题目

205. Isomorphic Strings

290. Word Pattern

LeetCode 题目总结

posted @ 2020-09-08 00:53  CNoodle  阅读(202)  评论(0)    收藏  举报