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

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/83351357
今日推荐