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.

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.

链接: http://leetcode.com/problems/word-pattern/

 1 public class Solution {
 2     public boolean wordPattern(String pattern, String str) {
 3         String[] parts = str.split(" ");
 4         if (pattern.length() != parts.length) return false;
 5         HashMap<Character, String> hcs = new HashMap<Character, String>();
 6         HashMap<String, Character> hsc = new HashMap<String, Character>();
 7 
 8         for(int i = 0; i < parts.length; i++) {
 9             if (!hsc.containsKey(parts[i]) && !hcs.containsKey(pattern.charAt(i))) {
10                 hsc.put(parts[i], pattern.charAt(i));
11                 hcs.put(pattern.charAt(i), parts[i]);
12             } else if (hsc.containsKey(parts[i]) && hcs.containsKey(pattern.charAt(i)) && hsc.get(parts[i]) == pattern.charAt(i) && hcs.get(pattern.charAt(i)).equals(parts[i])) {
13                 continue;
14             } else {
15                 return false;
16             }
17         }
18         return true;        
19     }
20 }

 

posted @ 2017-03-08 03:22  panini  阅读(139)  评论(0编辑  收藏  举报