LeetCode刷题Easy篇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-empty word in str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

十分钟尝试

之前做过一个类似的题目,思路基本一样,就是注意value已经存在的情况,返回false。 比如  a b  ,dog dog的情况,仅仅判断key是否存在map中不够,还需要判断value是否已经存在,如果是,但是key不同,必然是false

class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] words = str.split(" ");
        if (words.length != pattern.length()){
             return false;
        }
        Map<Character,String> map=new HashMap();
        for(int i=0;i<pattern.length();i++){
            Character curr=pattern.charAt(i);
            if(map.containsKey(curr)){
                if(!map.get(curr).equals(words[i])){
                    return false;
                }
            }
            else if(map.containsValue(words[i])){
                return false;
            }
            else{
                 map.put(curr,words[i]);
            }
           
        }
        return true;
      
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85092098