290. Word Pattern

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-emptyword in str.

Examples:

pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.

用hashmap来check是否一一对应

思路:build a hashmap -> make a for loop by string length ->

Check if the map has a key of pattern :

NO? -> check if the map has a value of str: Yes return false, No then put the both value in map.

Yes? ->check if map.get(pattern) equals to str: No return false; yes return true.

class Solution {
    public boolean wordPattern(String pattern, String str) {

        String[] strs = str.split(" ");

        if(strs.length != pattern.length()) return false;

        HashMap map = new HashMap<>();

        for(int i = 0 ;i < strs.length; i++){

            char p = pattern.charAt(i);

            if(map.containsKey(p) == false){

                if(map.containsValue(strs[i])) return false;

                map.put(p,strs[i]);
             }

            else if(map.get(p).equals(strs[i]) == false) return false;
        }

        return true;

    }
}

你可能感兴趣的:(Leetcode简单一刷)