LeetCode – 290. 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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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.

这道题目看起来简单,但是非常多的坑,非常建议大家自己做下,没思路的看下我注释。

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        // put all words in array
        List sl = new ArrayList();
        int pos = 0;
        for(int i=0;i<str.length();i++){
            if(str.charAt(i) == ' '){
                sl.add(str.substring(pos,i));
                pos = i+1;
            }
        }
        sl.add(str.substring(pos,str.length()));

        //check if array size == pattern length
        if(sl.size() != pattern.length()) return false;
        HashMap<String,String> map = new HashMap();
        for(int i=0;i<sl.size();i++){
            String s = new String(String.valueOf(pattern.charAt(i)));
            String l = new String(sl.get(i).toString());
            if(!map.containsKey(s)){
                if(map.containsValue(l)){
                    return false;
                }
                map.put(s,l);
            }
            else{
                String e = new String(map.get(s));
                if(!e.equals(l)){
                    return false;
                }
            }
        }
        return true;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。