leetcode: Word Pattern

来源:互联网 发布:金手指炒股软件下载 编辑:程序博客网 时间:2024/06/05 19:55

原题:
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<Character,String> mp = new HashMap<Character,String>();        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;    }
0 0