标签:
problem:
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:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."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
public class Solution { public boolean wordPattern(String pattern, String str) { if (pattern.isEmpty() || str.isEmpty()) { return false; } String[] s = str.split(" "); if (s.length != pattern.length()) { return false; } HashMap<Character, String> hashMap = new HashMap<Character, String>(); for (int i = 0; i < pattern.length(); i++) { if (hashMap.containsKey(pattern.charAt(i))) { if (!hashMap.get(pattern.charAt(i)).equals(s[i])) { return false; } } else if (hashMap.containsValue(s[i])) { return false; } else { hashMap.put(pattern.charAt(i), s[i]); } } return true; } }
标签:
原文地址:http://www.cnblogs.com/xiaoying1245970347/p/5178433.html