LeetCode:Word Pattern

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Word Pattern相关的知识,希望对你有一定的参考价值。

problem:

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.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

Solution:

 

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern.isEmpty() || str.isEmpty()) {
            return false;
        }
         
        String[] s = str.split(" ");
        if (s.length != pattern.length()) {
            return false;
        }
         
        HashMap<Character, String> hashMap = new HashMap<Character, String>();
        for (int i = 0; i < pattern.length(); i++) {
            if (hashMap.containsKey(pattern.charAt(i))) {
                if (!hashMap.get(pattern.charAt(i)).equals(s[i])) {
                    return false;
                }
            } else if (hashMap.containsValue(s[i])) {
                return false;
            } else {
                hashMap.put(pattern.charAt(i), s[i]);
            }
        }
         
        return true;
        
    }
}

 

以上是关于LeetCode:Word Pattern的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Word Pattern

csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us

[LeetCode]Word Break

[LeetCode]Word Search

LeetCode Word Ladder II

[Leetcode] word break 拆分词语