1. 程式人生 > >LeetCode刷題Easy篇Word Pattern

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;
      
    }
}