leetcode: 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.

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.

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

题意为给定一个模式串pattern和待匹配的串str,要判断str的模式是否与pattern匹配。

注意点:
- pattern中字符的个数与str中对应字符串个数相等。
- pattern中不相同的字符,在str中对应的字符串也不相等。

由映射关系可知此题需用到map,时间复杂度为O(n),为方便进行匹配判断,可将str划分成数组

public boolean wordPatern(String pattern,String str){
        Map mp = new HashMap();
        String[] array = str.split(" ");
        if(pattern.length()!=array.length)return false;//注意点1
        for (int i = 0; i < pattern.length(); i++) {
            if(!mp.containsKey(pattern.charAt(i))){
                if(mp.containsValue(array[i])) return false;//注意点2
                mp.put(pattern.charAt(i),array[i]);
            }
            else if(!mp.get(pattern.charAt(i)).equals(array[i])){   
                return false;
            }
        }
        return true;
    }

你可能感兴趣的:(算法,leetcode,string,leetcode)