LeetCode Word Pattern

原题链接在这里:https://leetcode.com/problems/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.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题解:

类似Isomorphic Strings.

通过建立HashMap 来存储 character 和 string 之间的对应来检查patter.

但这里要注意需要建立两个HashMap, 既要有character 到 string 的对应也要有string 到 character的对应。

e.g.  "aaaa", str = "dog cat cat dog" should return false. 但是若是没有 char 到 string 的对应就会返回true.

pattern = "abba", str = "dog dog dog dog" should return false. 但是若是没有 string 到 char的对应就会返回true.

Note: Character 类 也有一个equals(), 和 String的相同,使用起来也相同。

Time Complexity: O(pattern.length()). Space: O(pattern.length()).

AC Java:

 1 public class Solution {
 2     public boolean wordPattern(String pattern, String str) {
 3         if(pattern == null || pattern.length() == 0){
 4             return false;
 5         }
 6         if(str == null || str.length() == 0){
 7             return false;
 8         }
 9         String [] s = str.split("\s+");
10         if(pattern.length() != s.length){
11             return false;
12         }
13         //hm1 contains string -> character pair
14         HashMap<String,Character> hm1 = new HashMap<String,Character>();
15         for(int i = 0; i<s.length; i++){
16             if(!hm1.containsKey(s[i])){
17                 hm1.put(s[i],pattern.charAt(i));
18             }else{
19                 if(!hm1.get(s[i]).equals(pattern.charAt(i))){
20                     return false;
21                 }
22             }
23         }
24         //hm2 contains character -> string pair
25         HashMap<Character,String> hm2 = new HashMap<Character,String>();
26         for(int i = 0; i<pattern.length(); i++){
27             if(!hm2.containsKey(pattern.charAt(i))){
28                 hm2.put(pattern.charAt(i),s[i]);
29             }else{
30                 if(!hm2.get(pattern.charAt(i)).equals(s[i])){
31                     return false;
32                 }
33             }
34         }
35         return true;
36     }
37 }

 跟上Word Pattern II.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4903352.html