LeetCode—290. Word Pattern—Analysis and Code (Java)

LeetCode—290. Word Pattern [Word Pattern]—Analysis and Code [Java]

1. Title

Given a pattern and a string str, judge whether str follows the same pattern.
Follow here refers to complete matching. For example, there is a bidirectional connection between each letter in the pattern and each non-empty word in the string str.

Example 1:

输入: pattern = "abba", str = "dog cat cat dog"
输出: true

Example 2:

输入:pattern = "abba", str = "dog cat cat fish"
输出: false

Example 3:

输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false

Example 4:

输入: pattern = "abba", str = "dog dog dog dog"
输出: false

Explanation:
You can assume that pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Source: LeetCode
Link: https://leetcode-cn.com/problems/word-pattern The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Hash table

(1) Thinking

Construct a two-way hash table between pattern and str to determine whether there is a one-to-one correspondence.

(2) Code

class Solution {
    
    
    public boolean wordPattern(String pattern, String s) {
    
    
        char [] pat = pattern.toCharArray();
        String [] arr = s.split(" ");
        if (pat.length != arr.length)
            return false;
        
        Map<char, String> map = new HashMap<>();
        for (int i = 0; i < pat.length; i++) {
    
    
            if (map.get(pat[i]) == null)
                map.put(pat[i], arr[i]);
            else
                if (map.get(pat[i]) != arr[i])
                    return false;
        }

        return true;
    }
}

(3) Results

Execution time: 1 ms, beating 98.94% of users
in all Java submissions ; memory consumption: 36.3 MB, beating 90.50% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113000373
Recommended