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 <= 300pattern contains only lower-case English letters.1 <= s.length <= 3000s contains only lowercase English letters and spaces ' '.s does not contain any leading or trailing spaces.s are separated by a single space.和昨天做的205 Ismorphic String(http://t.csdn.cn/LzVxH)几乎是一样的,只是前面多加了个split string by space。熟练地采用昨天我觉得最好的那个map + set的方法做完了。
- class Solution {
- public boolean wordPattern(String pattern, String s) {
- Map<String, Character> map = new HashMap<>();
- Set<Character> used = new HashSet<>();
- String[] splited = s.split(" ");
- if (splited.length != pattern.length()) {
- return false;
- }
- for (int i = 0; i < splited.length; i++) {
- char c = pattern.charAt(i);
- if (map.containsKey(splited[i])) {
- if (c != map.get(splited[i])) {
- return false;
- }
- } else {
- if (used.contains(c)) {
- return false;
- }
- used.add(c);
- map.put(splited[i], c);
- }
- }
- return true;
- }
- }