码迷,mamicode.com
首页 > 编程语言 > 详细

290. Word Pattern java solutions

时间:2016-05-13 12:16:09      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

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

 

290. Word Pattern java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5487143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!