您的位置 首页 JAVA(2017)

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;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 290. Word Pattern》

发表评论

邮箱地址不会被公开。

返回顶部