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.

My solution:

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (str == null || pattern == null)
            return false;
        
        String[] words = str.split(" ");
        if(pattern.length() != words.length)
            return false;
        Map m = new HashMap();
        
        for(int i = 0 ; i < pattern.length(); i++) {
            char key = pattern.charAt(i);
            if(m.containsKey(key)) {
                if(!m.get(key).equals(words[i]))
                    return false;
                
            } else {
                if(m.containsValue(words[i]))
                    return false;
                m.put(key, words[i]);
            }
        }
        
        return true;
    }
}

Other's solution:

public boolean wordPattern(String pattern, String str) {
    String[] words = str.split(" ");
    if (words.length != pattern.length())
        return false;
    Map index = new HashMap();
    for (Integer i=0; i<words.length; ++i)
        if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
            return false;
    return true;
}

I go through the pattern letters and words in parallel and compare the indexes where they last appeared.

The return value of put method is the Value associates with the specified key in the map.

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问题: Given a pattern and a string str, find if str follows...
    Cloudox_阅读 3,157评论 0 0
  • Given a patternand a string str, find if strfollows the s...
    exialym阅读 1,215评论 0 0
  • Given a pattern and a string str, find if str follows the...
    a_void阅读 1,677评论 0 0
  • Given a pattern and a string str, find if str follows the...
    Jeanz阅读 2,087评论 0 0
  • 南锣鼓巷,一个我超级喜欢,满是小吃的地方! 这个地方,是一个完全没必要跟团的地方,城际下来坐地铁很方便,从地铁口出...
    汪坚强_a87a阅读 1,462评论 0 0