1. 程式人生 > >leetcode:(290) Word Pattern(java)

leetcode:(290) Word Pattern(java)

package LeetCode_HashTable;

/**
 * 題目:
 *      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
 *     Notes:
 *          You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
 */


import java.util.HashMap;
import java.util.Map;

public class WordPattern_290_1024 {
    public boolean WordPattern(String pattern,String str){
        if (pattern == null || pattern.length() == 0 ) {
            return false;
        }

        //將字串str利用空格將其拆分成字串陣列,其中每個字串應與模式串中相應的字元進行匹配
        String[] words = str.split(" ");
        if (pattern.length() != words.length) {
            return false;
        }
        Map map = new HashMap();

        for (Integer i = 0; i < words.length; i++) {
            //在java中,Map裡的put方法,如果key值不存在,則返回值是null,但是key值如果存在,
            // 則會返回原先被替換掉的value值.(當然,map中的key和value都允許是null).
            if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) {
                //若有匹配不成功。返回false
                return false;
            }
        }
        //匹配成功,返回true
        return true;
    }
}