Word Pattern
Given a pattern and a string s, find if s 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 s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
1 <= pattern.length <= 300
pattern contains only lower-case English letters.
1 <= s.length <= 3000
s contains only lowercase English letters and spaces ' '.
s does not contain any leading or trailing spaces.
All the words in s are separated by a single space.
思路一: 双射,和前面一道字符串双射的问题一模一样,不过用了 split 函数,用了正则分割速度会慢很多,可以自己实现分割函数
public boolean wordPattern(String pattern, String s) {
char[] pArr = pattern.toCharArray();
String[] sArr = s.split("\\s");
if (pArr.length != sArr.length) return false;
Map<Character, String> m1 = new HashMap<>();
Map<String, Character> m2 = new HashMap<>();
for (int i = 0; i < pArr.length; i++) {
char p = pArr[i];
String si = sArr[i];
if ((m1.containsKey(p) && m2.getOrDefault(si, Character.MIN_VALUE) != p) ||
(m2.containsKey(si) && !m1.getOrDefault(p, "").equals(si))) {
return false;
}
m1.put(p, si);
m2.put(si, p);
}
return true;
}
标签:false,String,pattern,dog,cat,si,easy,leetcode,290
From: https://www.cnblogs.com/iyiluo/p/16825901.html