跳转至

2022/01/17 - 290. Word Pattern

290. Word Pattern - Easy

Description

290. 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

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<String, Character> map1 = new HashMap<>();
        Map<Character, String> map2 = new HashMap<>();
        char[] chArr = pattern.toCharArray();
        String[] strArr = s.split(" ");
        if (chArr.length != strArr.length) return false;
        int n = chArr.length;
        for (int i = 0; i < n; i++) {
            char c = chArr[i];
            String str = strArr[i];
            if (!map1.containsKey(str) && !map2.containsKey(c)) {
                map1.put(str, c);
                map2.put(c, str);
            } else {
                if (!str.equals(map2.get(c)) || c != map1.get(str)) return false;
            }
        }
        return true;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> map = new HashMap<>();
        Set<String> set = new HashSet<>();
        char[] chArr = pattern.toCharArray();
        String[] strArr = s.split(" ");
        int n = chArr.length, m = strArr.length;
        if (n != m) return false;
        for (int i = 0; i < n; i++) {
            char c = chArr[i];
            String str = strArr[i];
            if (!map.containsKey(c)) {
                if (set.contains(str)) return false;
                map.put(c, str);
                set.add(str);
            } else {
                if (!str.equals(map.get(c))) return false;
            }
        }
        return true;
    }
}

评论

回到页面顶部