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.

比较简单的一道题目,可以先将str分割成字符数组,然后用哈希表来存储p中的字符以及对应字符数组中的字符串。其次我们还需要一个set来记录字符数组中的字符串是否已经被匹配过。代码如下:
public class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] string = str.split("\\s");
        HashMap<Character, String> hm = new HashMap<Character, String>();
        Set<String> set = new HashSet<String>();
        if(pattern.length() != string.length) return false;
        for(int i = 0; i < pattern.length(); i++) {
            if(hm.containsKey(pattern.charAt(i))) {
                if(!hm.get(pattern.charAt(i)).equals(string[i]))
                    return false;
            } else {
                if(set.contains(string[i])) {
                    return false;
                } else {
                    hm.put(pattern.charAt(i), string[i]);
                    set.add(string[i]);
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2279214
今日推荐