欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Word Pattern 博客分类: Leetcode 哈希字符串 

程序员文章站 2024-03-18 09:28:58
...
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;
    }
}
相关标签: 哈希 字符串