290. Word Pattern

来源:互联网 发布:iphone连mac导照片 编辑:程序博客网 时间:2024/06/09 15:01

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.

3ms 19.10%

public class WordPattern {public static boolean wordPattern(String pattern, String str) {String[] strs = str.split(" ");if (pattern.length() != strs.length)return false;Map<Character, String> map = new HashMap<Character, String>();for (int i = 0; i < pattern.length(); i++) {if (!map.containsKey(pattern.charAt(i))) {if (map.containsValue(strs[i]))return false;map.put(pattern.charAt(i), strs[i]);} else {if (strs[i].equals(map.get(pattern.charAt(i))))continue;elsereturn false;}}return true;}}

solution2

3ms 19.10%

This method used the property of the put method of HashMap, if the key has been existed  in the map, the new value is going to replace the old value and the returns the old value, if the key was not in the map, put method returns null

public static boolean wordPattern2(String pattern, String str) {                 if (pattern.isEmpty() || str.isEmpty()) {            return false;        }                 String[] s = str.split(" ");        if (s.length != pattern.length()) {            return false;        }                 @SuppressWarnings("rawtypes")        HashMap<Comparable, Integer> hashMap = new HashMap<Comparable, Integer>();        for (int i = 0; i < pattern.length(); i++) {            if (!Objects.equals(hashMap.put(pattern.charAt(i), i), hashMap.put(s[i], i)))                return false;        }                 return true;    }




0 0